From bc2446bb0203495ea709e09851a355cee410e761 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 29 Jun 2021 22:03:48 +0000 Subject: [PATCH 1/2] chore: use gapic-generator-python 0.50.3 fix: disable always_use_jwt_access Committer: @busunkim96 PiperOrigin-RevId: 382142900 Source-Link: https://github.com/googleapis/googleapis/commit/513440fda515f3c799c22a30e3906dcda325004e Source-Link: https://github.com/googleapis/googleapis-gen/commit/7b1e2c31233f79a704ec21ca410bf661d6bc68d0 --- owl-bot-staging/v1beta1/.coveragerc | 17 + owl-bot-staging/v1beta1/MANIFEST.in | 2 + owl-bot-staging/v1beta1/README.rst | 49 + owl-bot-staging/v1beta1/docs/conf.py | 376 +++ owl-bot-staging/v1beta1/docs/index.rst | 7 + .../catalog_service.rst | 10 + .../prediction_api_key_registry.rst | 10 + .../prediction_service.rst | 10 + .../recommendationengine_v1beta1/services.rst | 9 + .../recommendationengine_v1beta1/types.rst | 7 + .../user_event_service.rst | 10 + .../cloud/recommendationengine/__init__.py | 117 + .../cloud/recommendationengine/py.typed | 2 + .../recommendationengine_v1beta1/__init__.py | 118 + .../gapic_metadata.json | 215 ++ .../recommendationengine_v1beta1/py.typed | 2 + .../services/__init__.py | 15 + .../services/catalog_service/__init__.py | 22 + .../services/catalog_service/async_client.py | 761 +++++ .../services/catalog_service/client.py | 915 ++++++ .../services/catalog_service/pagers.py | 141 + .../catalog_service/transports/__init__.py | 33 + .../catalog_service/transports/base.py | 290 ++ .../catalog_service/transports/grpc.py | 412 +++ .../transports/grpc_asyncio.py | 416 +++ .../prediction_api_key_registry/__init__.py | 22 + .../async_client.py | 430 +++ .../prediction_api_key_registry/client.py | 605 ++++ .../prediction_api_key_registry/pagers.py | 140 + .../transports/__init__.py | 33 + .../transports/base.py | 218 ++ .../transports/grpc.py | 314 ++ .../transports/grpc_asyncio.py | 318 ++ .../services/prediction_service/__init__.py | 22 + .../prediction_service/async_client.py | 310 ++ .../services/prediction_service/client.py | 490 +++ .../services/prediction_service/pagers.py | 140 + .../prediction_service/transports/__init__.py | 33 + .../prediction_service/transports/base.py | 175 ++ .../prediction_service/transports/grpc.py | 256 ++ .../transports/grpc_asyncio.py | 260 ++ .../services/user_event_service/__init__.py | 22 + .../user_event_service/async_client.py | 847 ++++++ .../services/user_event_service/client.py | 999 ++++++ .../services/user_event_service/pagers.py | 141 + .../user_event_service/transports/__init__.py | 33 + .../user_event_service/transports/base.py | 269 ++ .../user_event_service/transports/grpc.py | 395 +++ .../transports/grpc_asyncio.py | 399 +++ .../types/__init__.py | 116 + .../types/catalog.py | 312 ++ .../types/catalog_service.py | 177 ++ .../types/common.py | 91 + .../types/import_.py | 373 +++ .../prediction_apikey_registry_service.py | 138 + .../types/prediction_service.py | 271 ++ .../types/recommendationengine_resources.py | 25 + .../types/user_event.py | 513 ++++ .../types/user_event_service.py | 289 ++ owl-bot-staging/v1beta1/mypy.ini | 3 + owl-bot-staging/v1beta1/noxfile.py | 132 + ...p_recommendationengine_v1beta1_keywords.py | 190 ++ owl-bot-staging/v1beta1/setup.py | 53 + owl-bot-staging/v1beta1/tests/__init__.py | 16 + .../v1beta1/tests/unit/__init__.py | 16 + .../v1beta1/tests/unit/gapic/__init__.py | 16 + .../recommendationengine_v1beta1/__init__.py | 16 + .../test_catalog_service.py | 2676 +++++++++++++++++ .../test_prediction_api_key_registry.py | 1840 ++++++++++++ .../test_prediction_service.py | 1377 +++++++++ .../test_user_event_service.py | 2394 +++++++++++++++ 71 files changed, 21871 insertions(+) create mode 100644 owl-bot-staging/v1beta1/.coveragerc create mode 100644 owl-bot-staging/v1beta1/MANIFEST.in create mode 100644 owl-bot-staging/v1beta1/README.rst create mode 100644 owl-bot-staging/v1beta1/docs/conf.py create mode 100644 owl-bot-staging/v1beta1/docs/index.rst create mode 100644 owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/catalog_service.rst create mode 100644 owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/prediction_api_key_registry.rst create mode 100644 owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/prediction_service.rst create mode 100644 owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/services.rst create mode 100644 owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/types.rst create mode 100644 owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/user_event_service.rst create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine/py.typed create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/gapic_metadata.json create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/py.typed create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/async_client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/pagers.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/base.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/async_client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/pagers.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/base.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/async_client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/pagers.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/base.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/async_client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/pagers.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/base.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/catalog.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/catalog_service.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/common.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/import_.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/prediction_apikey_registry_service.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/prediction_service.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/recommendationengine_resources.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/user_event.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/user_event_service.py create mode 100644 owl-bot-staging/v1beta1/mypy.ini create mode 100644 owl-bot-staging/v1beta1/noxfile.py create mode 100644 owl-bot-staging/v1beta1/scripts/fixup_recommendationengine_v1beta1_keywords.py create mode 100644 owl-bot-staging/v1beta1/setup.py create mode 100644 owl-bot-staging/v1beta1/tests/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_catalog_service.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_api_key_registry.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_user_event_service.py diff --git a/owl-bot-staging/v1beta1/.coveragerc b/owl-bot-staging/v1beta1/.coveragerc new file mode 100644 index 00000000..41724c80 --- /dev/null +++ b/owl-bot-staging/v1beta1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/recommendationengine/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1beta1/MANIFEST.in b/owl-bot-staging/v1beta1/MANIFEST.in new file mode 100644 index 00000000..5054f413 --- /dev/null +++ b/owl-bot-staging/v1beta1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/recommendationengine *.py +recursive-include google/cloud/recommendationengine_v1beta1 *.py diff --git a/owl-bot-staging/v1beta1/README.rst b/owl-bot-staging/v1beta1/README.rst new file mode 100644 index 00000000..11130784 --- /dev/null +++ b/owl-bot-staging/v1beta1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Recommendationengine 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 Recommendationengine 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/v1beta1/docs/conf.py b/owl-bot-staging/v1beta1/docs/conf.py new file mode 100644 index 00000000..1bbaeeeb --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-recommendations-ai documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "1.6.3" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-cloud-recommendations-ai" +copyright = u"2020, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google 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-recommendations-ai-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + master_doc, + "google-cloud-recommendations-ai.tex", + u"google-cloud-recommendations-ai Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + master_doc, + "google-cloud-recommendations-ai", + u"Google Cloud Recommendationengine Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "google-cloud-recommendations-ai", + u"google-cloud-recommendations-ai Documentation", + author, + "google-cloud-recommendations-ai", + "GAPIC library for Google Cloud Recommendationengine 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/v1beta1/docs/index.rst b/owl-bot-staging/v1beta1/docs/index.rst new file mode 100644 index 00000000..b7e1db6b --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + recommendationengine_v1beta1/services + recommendationengine_v1beta1/types diff --git a/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/catalog_service.rst b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/catalog_service.rst new file mode 100644 index 00000000..48f7c814 --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/catalog_service.rst @@ -0,0 +1,10 @@ +CatalogService +-------------------------------- + +.. automodule:: google.cloud.recommendationengine_v1beta1.services.catalog_service + :members: + :inherited-members: + +.. automodule:: google.cloud.recommendationengine_v1beta1.services.catalog_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/prediction_api_key_registry.rst b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/prediction_api_key_registry.rst new file mode 100644 index 00000000..74874c31 --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/prediction_api_key_registry.rst @@ -0,0 +1,10 @@ +PredictionApiKeyRegistry +------------------------------------------ + +.. automodule:: google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry + :members: + :inherited-members: + +.. automodule:: google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/prediction_service.rst b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/prediction_service.rst new file mode 100644 index 00000000..7d2fc56d --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/prediction_service.rst @@ -0,0 +1,10 @@ +PredictionService +----------------------------------- + +.. automodule:: google.cloud.recommendationengine_v1beta1.services.prediction_service + :members: + :inherited-members: + +.. automodule:: google.cloud.recommendationengine_v1beta1.services.prediction_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/services.rst b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/services.rst new file mode 100644 index 00000000..ced8732d --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/services.rst @@ -0,0 +1,9 @@ +Services for Google Cloud Recommendationengine v1beta1 API +========================================================== +.. toctree:: + :maxdepth: 2 + + catalog_service + prediction_api_key_registry + prediction_service + user_event_service diff --git a/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/types.rst b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/types.rst new file mode 100644 index 00000000..679552ed --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Recommendationengine v1beta1 API +======================================================= + +.. automodule:: google.cloud.recommendationengine_v1beta1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/user_event_service.rst b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/user_event_service.rst new file mode 100644 index 00000000..728ec7e9 --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/user_event_service.rst @@ -0,0 +1,10 @@ +UserEventService +---------------------------------- + +.. automodule:: google.cloud.recommendationengine_v1beta1.services.user_event_service + :members: + :inherited-members: + +.. automodule:: google.cloud.recommendationengine_v1beta1.services.user_event_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine/__init__.py new file mode 100644 index 00000000..61922786 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine/__init__.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.cloud.recommendationengine_v1beta1.services.catalog_service.client import CatalogServiceClient +from google.cloud.recommendationengine_v1beta1.services.catalog_service.async_client import CatalogServiceAsyncClient +from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry.client import PredictionApiKeyRegistryClient +from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry.async_client import PredictionApiKeyRegistryAsyncClient +from google.cloud.recommendationengine_v1beta1.services.prediction_service.client import PredictionServiceClient +from google.cloud.recommendationengine_v1beta1.services.prediction_service.async_client import PredictionServiceAsyncClient +from google.cloud.recommendationengine_v1beta1.services.user_event_service.client import UserEventServiceClient +from google.cloud.recommendationengine_v1beta1.services.user_event_service.async_client import UserEventServiceAsyncClient + +from google.cloud.recommendationengine_v1beta1.types.catalog import CatalogItem +from google.cloud.recommendationengine_v1beta1.types.catalog import Image +from google.cloud.recommendationengine_v1beta1.types.catalog import ProductCatalogItem +from google.cloud.recommendationengine_v1beta1.types.catalog_service import CreateCatalogItemRequest +from google.cloud.recommendationengine_v1beta1.types.catalog_service import DeleteCatalogItemRequest +from google.cloud.recommendationengine_v1beta1.types.catalog_service import GetCatalogItemRequest +from google.cloud.recommendationengine_v1beta1.types.catalog_service import ListCatalogItemsRequest +from google.cloud.recommendationengine_v1beta1.types.catalog_service import ListCatalogItemsResponse +from google.cloud.recommendationengine_v1beta1.types.catalog_service import UpdateCatalogItemRequest +from google.cloud.recommendationengine_v1beta1.types.common import FeatureMap +from google.cloud.recommendationengine_v1beta1.types.import_ import CatalogInlineSource +from google.cloud.recommendationengine_v1beta1.types.import_ import GcsSource +from google.cloud.recommendationengine_v1beta1.types.import_ import ImportCatalogItemsRequest +from google.cloud.recommendationengine_v1beta1.types.import_ import ImportCatalogItemsResponse +from google.cloud.recommendationengine_v1beta1.types.import_ import ImportErrorsConfig +from google.cloud.recommendationengine_v1beta1.types.import_ import ImportMetadata +from google.cloud.recommendationengine_v1beta1.types.import_ import ImportUserEventsRequest +from google.cloud.recommendationengine_v1beta1.types.import_ import ImportUserEventsResponse +from google.cloud.recommendationengine_v1beta1.types.import_ import InputConfig +from google.cloud.recommendationengine_v1beta1.types.import_ import UserEventImportSummary +from google.cloud.recommendationengine_v1beta1.types.import_ import UserEventInlineSource +from google.cloud.recommendationengine_v1beta1.types.prediction_apikey_registry_service import CreatePredictionApiKeyRegistrationRequest +from google.cloud.recommendationengine_v1beta1.types.prediction_apikey_registry_service import DeletePredictionApiKeyRegistrationRequest +from google.cloud.recommendationengine_v1beta1.types.prediction_apikey_registry_service import ListPredictionApiKeyRegistrationsRequest +from google.cloud.recommendationengine_v1beta1.types.prediction_apikey_registry_service import ListPredictionApiKeyRegistrationsResponse +from google.cloud.recommendationengine_v1beta1.types.prediction_apikey_registry_service import PredictionApiKeyRegistration +from google.cloud.recommendationengine_v1beta1.types.prediction_service import PredictRequest +from google.cloud.recommendationengine_v1beta1.types.prediction_service import PredictResponse +from google.cloud.recommendationengine_v1beta1.types.user_event import EventDetail +from google.cloud.recommendationengine_v1beta1.types.user_event import ProductDetail +from google.cloud.recommendationengine_v1beta1.types.user_event import ProductEventDetail +from google.cloud.recommendationengine_v1beta1.types.user_event import PurchaseTransaction +from google.cloud.recommendationengine_v1beta1.types.user_event import UserEvent +from google.cloud.recommendationengine_v1beta1.types.user_event import UserInfo +from google.cloud.recommendationengine_v1beta1.types.user_event_service import CollectUserEventRequest +from google.cloud.recommendationengine_v1beta1.types.user_event_service import ListUserEventsRequest +from google.cloud.recommendationengine_v1beta1.types.user_event_service import ListUserEventsResponse +from google.cloud.recommendationengine_v1beta1.types.user_event_service import PurgeUserEventsMetadata +from google.cloud.recommendationengine_v1beta1.types.user_event_service import PurgeUserEventsRequest +from google.cloud.recommendationengine_v1beta1.types.user_event_service import PurgeUserEventsResponse +from google.cloud.recommendationengine_v1beta1.types.user_event_service import WriteUserEventRequest + +__all__ = ('CatalogServiceClient', + 'CatalogServiceAsyncClient', + 'PredictionApiKeyRegistryClient', + 'PredictionApiKeyRegistryAsyncClient', + 'PredictionServiceClient', + 'PredictionServiceAsyncClient', + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', + 'CatalogItem', + 'Image', + 'ProductCatalogItem', + 'CreateCatalogItemRequest', + 'DeleteCatalogItemRequest', + 'GetCatalogItemRequest', + 'ListCatalogItemsRequest', + 'ListCatalogItemsResponse', + 'UpdateCatalogItemRequest', + 'FeatureMap', + 'CatalogInlineSource', + 'GcsSource', + 'ImportCatalogItemsRequest', + 'ImportCatalogItemsResponse', + 'ImportErrorsConfig', + 'ImportMetadata', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'InputConfig', + 'UserEventImportSummary', + 'UserEventInlineSource', + 'CreatePredictionApiKeyRegistrationRequest', + 'DeletePredictionApiKeyRegistrationRequest', + 'ListPredictionApiKeyRegistrationsRequest', + 'ListPredictionApiKeyRegistrationsResponse', + 'PredictionApiKeyRegistration', + 'PredictRequest', + 'PredictResponse', + 'EventDetail', + 'ProductDetail', + 'ProductEventDetail', + 'PurchaseTransaction', + 'UserEvent', + 'UserInfo', + 'CollectUserEventRequest', + 'ListUserEventsRequest', + 'ListUserEventsResponse', + 'PurgeUserEventsMetadata', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine/py.typed b/owl-bot-staging/v1beta1/google/cloud/recommendationengine/py.typed new file mode 100644 index 00000000..41689a36 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-recommendations-ai package uses inline types. diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/__init__.py new file mode 100644 index 00000000..532c2908 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/__init__.py @@ -0,0 +1,118 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.catalog_service import CatalogServiceClient +from .services.catalog_service import CatalogServiceAsyncClient +from .services.prediction_api_key_registry import PredictionApiKeyRegistryClient +from .services.prediction_api_key_registry import PredictionApiKeyRegistryAsyncClient +from .services.prediction_service import PredictionServiceClient +from .services.prediction_service import PredictionServiceAsyncClient +from .services.user_event_service import UserEventServiceClient +from .services.user_event_service import UserEventServiceAsyncClient + +from .types.catalog import CatalogItem +from .types.catalog import Image +from .types.catalog import ProductCatalogItem +from .types.catalog_service import CreateCatalogItemRequest +from .types.catalog_service import DeleteCatalogItemRequest +from .types.catalog_service import GetCatalogItemRequest +from .types.catalog_service import ListCatalogItemsRequest +from .types.catalog_service import ListCatalogItemsResponse +from .types.catalog_service import UpdateCatalogItemRequest +from .types.common import FeatureMap +from .types.import_ import CatalogInlineSource +from .types.import_ import GcsSource +from .types.import_ import ImportCatalogItemsRequest +from .types.import_ import ImportCatalogItemsResponse +from .types.import_ import ImportErrorsConfig +from .types.import_ import ImportMetadata +from .types.import_ import ImportUserEventsRequest +from .types.import_ import ImportUserEventsResponse +from .types.import_ import InputConfig +from .types.import_ import UserEventImportSummary +from .types.import_ import UserEventInlineSource +from .types.prediction_apikey_registry_service import CreatePredictionApiKeyRegistrationRequest +from .types.prediction_apikey_registry_service import DeletePredictionApiKeyRegistrationRequest +from .types.prediction_apikey_registry_service import ListPredictionApiKeyRegistrationsRequest +from .types.prediction_apikey_registry_service import ListPredictionApiKeyRegistrationsResponse +from .types.prediction_apikey_registry_service import PredictionApiKeyRegistration +from .types.prediction_service import PredictRequest +from .types.prediction_service import PredictResponse +from .types.user_event import EventDetail +from .types.user_event import ProductDetail +from .types.user_event import ProductEventDetail +from .types.user_event import PurchaseTransaction +from .types.user_event import UserEvent +from .types.user_event import UserInfo +from .types.user_event_service import CollectUserEventRequest +from .types.user_event_service import ListUserEventsRequest +from .types.user_event_service import ListUserEventsResponse +from .types.user_event_service import PurgeUserEventsMetadata +from .types.user_event_service import PurgeUserEventsRequest +from .types.user_event_service import PurgeUserEventsResponse +from .types.user_event_service import WriteUserEventRequest + +__all__ = ( + 'CatalogServiceAsyncClient', + 'PredictionApiKeyRegistryAsyncClient', + 'PredictionServiceAsyncClient', + 'UserEventServiceAsyncClient', +'CatalogInlineSource', +'CatalogItem', +'CatalogServiceClient', +'CollectUserEventRequest', +'CreateCatalogItemRequest', +'CreatePredictionApiKeyRegistrationRequest', +'DeleteCatalogItemRequest', +'DeletePredictionApiKeyRegistrationRequest', +'EventDetail', +'FeatureMap', +'GcsSource', +'GetCatalogItemRequest', +'Image', +'ImportCatalogItemsRequest', +'ImportCatalogItemsResponse', +'ImportErrorsConfig', +'ImportMetadata', +'ImportUserEventsRequest', +'ImportUserEventsResponse', +'InputConfig', +'ListCatalogItemsRequest', +'ListCatalogItemsResponse', +'ListPredictionApiKeyRegistrationsRequest', +'ListPredictionApiKeyRegistrationsResponse', +'ListUserEventsRequest', +'ListUserEventsResponse', +'PredictRequest', +'PredictResponse', +'PredictionApiKeyRegistration', +'PredictionApiKeyRegistryClient', +'PredictionServiceClient', +'ProductCatalogItem', +'ProductDetail', +'ProductEventDetail', +'PurchaseTransaction', +'PurgeUserEventsMetadata', +'PurgeUserEventsRequest', +'PurgeUserEventsResponse', +'UpdateCatalogItemRequest', +'UserEvent', +'UserEventImportSummary', +'UserEventInlineSource', +'UserEventServiceClient', +'UserInfo', +'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/gapic_metadata.json b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/gapic_metadata.json new file mode 100644 index 00000000..b5ae877c --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/gapic_metadata.json @@ -0,0 +1,215 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.recommendationengine_v1beta1", + "protoPackage": "google.cloud.recommendationengine.v1beta1", + "schema": "1.0", + "services": { + "CatalogService": { + "clients": { + "grpc": { + "libraryClient": "CatalogServiceClient", + "rpcs": { + "CreateCatalogItem": { + "methods": [ + "create_catalog_item" + ] + }, + "DeleteCatalogItem": { + "methods": [ + "delete_catalog_item" + ] + }, + "GetCatalogItem": { + "methods": [ + "get_catalog_item" + ] + }, + "ImportCatalogItems": { + "methods": [ + "import_catalog_items" + ] + }, + "ListCatalogItems": { + "methods": [ + "list_catalog_items" + ] + }, + "UpdateCatalogItem": { + "methods": [ + "update_catalog_item" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CatalogServiceAsyncClient", + "rpcs": { + "CreateCatalogItem": { + "methods": [ + "create_catalog_item" + ] + }, + "DeleteCatalogItem": { + "methods": [ + "delete_catalog_item" + ] + }, + "GetCatalogItem": { + "methods": [ + "get_catalog_item" + ] + }, + "ImportCatalogItems": { + "methods": [ + "import_catalog_items" + ] + }, + "ListCatalogItems": { + "methods": [ + "list_catalog_items" + ] + }, + "UpdateCatalogItem": { + "methods": [ + "update_catalog_item" + ] + } + } + } + } + }, + "PredictionApiKeyRegistry": { + "clients": { + "grpc": { + "libraryClient": "PredictionApiKeyRegistryClient", + "rpcs": { + "CreatePredictionApiKeyRegistration": { + "methods": [ + "create_prediction_api_key_registration" + ] + }, + "DeletePredictionApiKeyRegistration": { + "methods": [ + "delete_prediction_api_key_registration" + ] + }, + "ListPredictionApiKeyRegistrations": { + "methods": [ + "list_prediction_api_key_registrations" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PredictionApiKeyRegistryAsyncClient", + "rpcs": { + "CreatePredictionApiKeyRegistration": { + "methods": [ + "create_prediction_api_key_registration" + ] + }, + "DeletePredictionApiKeyRegistration": { + "methods": [ + "delete_prediction_api_key_registration" + ] + }, + "ListPredictionApiKeyRegistrations": { + "methods": [ + "list_prediction_api_key_registrations" + ] + } + } + } + } + }, + "PredictionService": { + "clients": { + "grpc": { + "libraryClient": "PredictionServiceClient", + "rpcs": { + "Predict": { + "methods": [ + "predict" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PredictionServiceAsyncClient", + "rpcs": { + "Predict": { + "methods": [ + "predict" + ] + } + } + } + } + }, + "UserEventService": { + "clients": { + "grpc": { + "libraryClient": "UserEventServiceClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "ListUserEvents": { + "methods": [ + "list_user_events" + ] + }, + "PurgeUserEvents": { + "methods": [ + "purge_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + }, + "grpc-async": { + "libraryClient": "UserEventServiceAsyncClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "ListUserEvents": { + "methods": [ + "list_user_events" + ] + }, + "PurgeUserEvents": { + "methods": [ + "purge_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/py.typed b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/py.typed new file mode 100644 index 00000000..41689a36 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-recommendations-ai package uses inline types. diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/__init__.py new file mode 100644 index 00000000..316640d9 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import CatalogServiceClient +from .async_client import CatalogServiceAsyncClient + +__all__ = ( + 'CatalogServiceClient', + 'CatalogServiceAsyncClient', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/async_client.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/async_client.py new file mode 100644 index 00000000..605dafc2 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/async_client.py @@ -0,0 +1,761 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.recommendationengine_v1beta1.services.catalog_service import pagers +from google.cloud.recommendationengine_v1beta1.types import catalog +from google.cloud.recommendationengine_v1beta1.types import catalog_service +from google.cloud.recommendationengine_v1beta1.types import common +from google.cloud.recommendationengine_v1beta1.types import import_ +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport +from .client import CatalogServiceClient + + +class CatalogServiceAsyncClient: + """Service for ingesting catalog information of the customer's + website. + """ + + _client: CatalogServiceClient + + DEFAULT_ENDPOINT = CatalogServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CatalogServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(CatalogServiceClient.catalog_path) + parse_catalog_path = staticmethod(CatalogServiceClient.parse_catalog_path) + catalog_item_path_path = staticmethod(CatalogServiceClient.catalog_item_path_path) + parse_catalog_item_path_path = staticmethod(CatalogServiceClient.parse_catalog_item_path_path) + common_billing_account_path = staticmethod(CatalogServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CatalogServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CatalogServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CatalogServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CatalogServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CatalogServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CatalogServiceClient.common_project_path) + parse_common_project_path = staticmethod(CatalogServiceClient.parse_common_project_path) + common_location_path = staticmethod(CatalogServiceClient.common_location_path) + parse_common_location_path = staticmethod(CatalogServiceClient.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: + CatalogServiceAsyncClient: The constructed client. + """ + return CatalogServiceClient.from_service_account_info.__func__(CatalogServiceAsyncClient, 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: + CatalogServiceAsyncClient: The constructed client. + """ + return CatalogServiceClient.from_service_account_file.__func__(CatalogServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> CatalogServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CatalogServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(CatalogServiceClient).get_transport_class, type(CatalogServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, CatalogServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the catalog service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CatalogServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CatalogServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_catalog_item(self, + request: catalog_service.CreateCatalogItemRequest = None, + *, + parent: str = None, + catalog_item: catalog.CatalogItem = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CatalogItem: + r"""Creates a catalog item. + + Args: + request (:class:`google.cloud.recommendationengine_v1beta1.types.CreateCatalogItemRequest`): + The request object. Request message for + CreateCatalogItem method. + parent (:class:`str`): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + catalog_item (:class:`google.cloud.recommendationengine_v1beta1.types.CatalogItem`): + Required. The catalog item to create. + This corresponds to the ``catalog_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.recommendationengine_v1beta1.types.CatalogItem: + CatalogItem captures all metadata + information of items to be recommended. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, catalog_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.") + + request = catalog_service.CreateCatalogItemRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if catalog_item is not None: + request.catalog_item = catalog_item + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_catalog_item, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_catalog_item(self, + request: catalog_service.GetCatalogItemRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CatalogItem: + r"""Gets a specific catalog item. + + Args: + request (:class:`google.cloud.recommendationengine_v1beta1.types.GetCatalogItemRequest`): + The request object. Request message for GetCatalogItem + method. + name (:class:`str`): + Required. Full resource name of catalog item, such as + ``projects/*/locations/global/catalogs/default_catalog/catalogitems/some_catalog_item_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.recommendationengine_v1beta1.types.CatalogItem: + CatalogItem captures all metadata + information of items to be recommended. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.GetCatalogItemRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_catalog_item, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_catalog_items(self, + request: catalog_service.ListCatalogItemsRequest = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCatalogItemsAsyncPager: + r"""Gets a list of catalog items. + + Args: + request (:class:`google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsRequest`): + The request object. Request message for ListCatalogItems + method. + parent (:class:`str`): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Optional. A filter to apply on the + list results. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recommendationengine_v1beta1.services.catalog_service.pagers.ListCatalogItemsAsyncPager: + Response message for ListCatalogItems + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, filter]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.ListCatalogItemsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_catalog_items, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListCatalogItemsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_catalog_item(self, + request: catalog_service.UpdateCatalogItemRequest = None, + *, + name: str = None, + catalog_item: catalog.CatalogItem = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CatalogItem: + r"""Updates a catalog item. Partial updating is + supported. Non-existing items will be created. + + Args: + request (:class:`google.cloud.recommendationengine_v1beta1.types.UpdateCatalogItemRequest`): + The request object. Request message for + UpdateCatalogItem method. + name (:class:`str`): + Required. Full resource name of catalog item, such as + "projects/*/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_id". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + catalog_item (:class:`google.cloud.recommendationengine_v1beta1.types.CatalogItem`): + Required. The catalog item to update/create. The + 'catalog_item_id' field has to match that in the 'name'. + + This corresponds to the ``catalog_item`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Indicates which fields in + the provided 'item' to update. If not + set, will by default update all fields. + + 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.recommendationengine_v1beta1.types.CatalogItem: + CatalogItem captures all metadata + information of items to be recommended. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, catalog_item, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.UpdateCatalogItemRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if catalog_item is not None: + request.catalog_item = catalog_item + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_catalog_item, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_catalog_item(self, + request: catalog_service.DeleteCatalogItemRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a catalog item. + + Args: + request (:class:`google.cloud.recommendationengine_v1beta1.types.DeleteCatalogItemRequest`): + The request object. Request message for + DeleteCatalogItem method. + name (:class:`str`): + Required. Full resource name of catalog item, such as + ``projects/*/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_id``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = catalog_service.DeleteCatalogItemRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_catalog_item, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def import_catalog_items(self, + request: import_.ImportCatalogItemsRequest = None, + *, + parent: str = None, + request_id: str = None, + input_config: import_.InputConfig = None, + errors_config: import_.ImportErrorsConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of multiple catalog items. Request + processing may be synchronous. No partial updating + supported. Non-existing items will be created. + + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully updated. + + Args: + request (:class:`google.cloud.recommendationengine_v1beta1.types.ImportCatalogItemsRequest`): + The request object. Request message for Import methods. + parent (:class:`str`): + Required. + ``projects/1234/locations/global/catalogs/default_catalog`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + request_id (:class:`str`): + Optional. Unique identifier provided + by client, within the ancestor dataset + scope. Ensures idempotency and used for + request deduplication. Server-generated + if unspecified. Up to 128 characters + long. This is returned as + google.longrunning.Operation.name in the + response. + + This corresponds to the ``request_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + input_config (:class:`google.cloud.recommendationengine_v1beta1.types.InputConfig`): + Required. The desired input location + of the data. + + This corresponds to the ``input_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + errors_config (:class:`google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig`): + Optional. The desired location of + errors incurred during the Import. + + This corresponds to the ``errors_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.recommendationengine_v1beta1.types.ImportCatalogItemsResponse` Response of the ImportCatalogItemsRequest. If the long running + operation is done, then this message is returned by + the google.longrunning.Operations.response field if + the operation was successful. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, request_id, input_config, errors_config]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = import_.ImportCatalogItemsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if request_id is not None: + request.request_id = request_id + if input_config is not None: + request.input_config = input_config + if errors_config is not None: + request.errors_config = errors_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_catalog_items, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_.ImportCatalogItemsResponse, + metadata_type=import_.ImportMetadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-recommendations-ai", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CatalogServiceAsyncClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/client.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/client.py new file mode 100644 index 00000000..d5cf1535 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/client.py @@ -0,0 +1,915 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.recommendationengine_v1beta1.services.catalog_service import pagers +from google.cloud.recommendationengine_v1beta1.types import catalog +from google.cloud.recommendationengine_v1beta1.types import catalog_service +from google.cloud.recommendationengine_v1beta1.types import common +from google.cloud.recommendationengine_v1beta1.types import import_ +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CatalogServiceGrpcTransport +from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport + + +class CatalogServiceClientMeta(type): + """Metaclass for the CatalogService 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[CatalogServiceTransport]] + _transport_registry["grpc"] = CatalogServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CatalogServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[CatalogServiceTransport]: + """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 CatalogServiceClient(metaclass=CatalogServiceClientMeta): + """Service for ingesting catalog information of the customer's + website. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "recommendationengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CatalogServiceClient: 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: + CatalogServiceClient: 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) -> CatalogServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CatalogServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str,str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def catalog_item_path_path(project: str,location: str,catalog: str,) -> str: + """Returns a fully-qualified catalog_item_path string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/catalogItems/{catalog_item_path=**}".format(project=project, location=location, catalog=catalog, ) + + @staticmethod + def parse_catalog_item_path_path(path: str) -> Dict[str,str]: + """Parses a catalog_item_path path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/catalogItems/{catalog_item_path=**}$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CatalogServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the catalog service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CatalogServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, CatalogServiceTransport): + # transport is a CatalogServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def create_catalog_item(self, + request: catalog_service.CreateCatalogItemRequest = None, + *, + parent: str = None, + catalog_item: catalog.CatalogItem = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CatalogItem: + r"""Creates a catalog item. + + Args: + request (google.cloud.recommendationengine_v1beta1.types.CreateCatalogItemRequest): + The request object. Request message for + CreateCatalogItem method. + parent (str): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + catalog_item (google.cloud.recommendationengine_v1beta1.types.CatalogItem): + Required. The catalog item to create. + This corresponds to the ``catalog_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.recommendationengine_v1beta1.types.CatalogItem: + CatalogItem captures all metadata + information of items to be recommended. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, catalog_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.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.CreateCatalogItemRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.CreateCatalogItemRequest): + request = catalog_service.CreateCatalogItemRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if catalog_item is not None: + request.catalog_item = catalog_item + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_catalog_item] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_catalog_item(self, + request: catalog_service.GetCatalogItemRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CatalogItem: + r"""Gets a specific catalog item. + + Args: + request (google.cloud.recommendationengine_v1beta1.types.GetCatalogItemRequest): + The request object. Request message for GetCatalogItem + method. + name (str): + Required. Full resource name of catalog item, such as + ``projects/*/locations/global/catalogs/default_catalog/catalogitems/some_catalog_item_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.recommendationengine_v1beta1.types.CatalogItem: + CatalogItem captures all metadata + information of items to be recommended. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.GetCatalogItemRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.GetCatalogItemRequest): + request = catalog_service.GetCatalogItemRequest(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_catalog_item] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_catalog_items(self, + request: catalog_service.ListCatalogItemsRequest = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCatalogItemsPager: + r"""Gets a list of catalog items. + + Args: + request (google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsRequest): + The request object. Request message for ListCatalogItems + method. + parent (str): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + Optional. A filter to apply on the + list results. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recommendationengine_v1beta1.services.catalog_service.pagers.ListCatalogItemsPager: + Response message for ListCatalogItems + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, filter]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.ListCatalogItemsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.ListCatalogItemsRequest): + request = catalog_service.ListCatalogItemsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_catalog_items] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListCatalogItemsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_catalog_item(self, + request: catalog_service.UpdateCatalogItemRequest = None, + *, + name: str = None, + catalog_item: catalog.CatalogItem = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CatalogItem: + r"""Updates a catalog item. Partial updating is + supported. Non-existing items will be created. + + Args: + request (google.cloud.recommendationengine_v1beta1.types.UpdateCatalogItemRequest): + The request object. Request message for + UpdateCatalogItem method. + name (str): + Required. Full resource name of catalog item, such as + "projects/*/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_id". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + catalog_item (google.cloud.recommendationengine_v1beta1.types.CatalogItem): + Required. The catalog item to update/create. The + 'catalog_item_id' field has to match that in the 'name'. + + This corresponds to the ``catalog_item`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Indicates which fields in + the provided 'item' to update. If not + set, will by default update all fields. + + 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.recommendationengine_v1beta1.types.CatalogItem: + CatalogItem captures all metadata + information of items to be recommended. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, catalog_item, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.UpdateCatalogItemRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.UpdateCatalogItemRequest): + request = catalog_service.UpdateCatalogItemRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if catalog_item is not None: + request.catalog_item = catalog_item + 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_catalog_item] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_catalog_item(self, + request: catalog_service.DeleteCatalogItemRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a catalog item. + + Args: + request (google.cloud.recommendationengine_v1beta1.types.DeleteCatalogItemRequest): + The request object. Request message for + DeleteCatalogItem method. + name (str): + Required. Full resource name of catalog item, such as + ``projects/*/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_id``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a catalog_service.DeleteCatalogItemRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.DeleteCatalogItemRequest): + request = catalog_service.DeleteCatalogItemRequest(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_catalog_item] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def import_catalog_items(self, + request: import_.ImportCatalogItemsRequest = None, + *, + parent: str = None, + request_id: str = None, + input_config: import_.InputConfig = None, + errors_config: import_.ImportErrorsConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of multiple catalog items. Request + processing may be synchronous. No partial updating + supported. Non-existing items will be created. + + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully updated. + + Args: + request (google.cloud.recommendationengine_v1beta1.types.ImportCatalogItemsRequest): + The request object. Request message for Import methods. + parent (str): + Required. + ``projects/1234/locations/global/catalogs/default_catalog`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + request_id (str): + Optional. Unique identifier provided + by client, within the ancestor dataset + scope. Ensures idempotency and used for + request deduplication. Server-generated + if unspecified. Up to 128 characters + long. This is returned as + google.longrunning.Operation.name in the + response. + + This corresponds to the ``request_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + input_config (google.cloud.recommendationengine_v1beta1.types.InputConfig): + Required. The desired input location + of the data. + + This corresponds to the ``input_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + errors_config (google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig): + Optional. The desired location of + errors incurred during the Import. + + This corresponds to the ``errors_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.recommendationengine_v1beta1.types.ImportCatalogItemsResponse` Response of the ImportCatalogItemsRequest. If the long running + operation is done, then this message is returned by + the google.longrunning.Operations.response field if + the operation was successful. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, request_id, input_config, errors_config]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a import_.ImportCatalogItemsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_.ImportCatalogItemsRequest): + request = import_.ImportCatalogItemsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if request_id is not None: + request.request_id = request_id + if input_config is not None: + request.input_config = input_config + if errors_config is not None: + request.errors_config = errors_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_catalog_items] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_.ImportCatalogItemsResponse, + metadata_type=import_.ImportMetadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-recommendations-ai", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "CatalogServiceClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/pagers.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/pagers.py new file mode 100644 index 00000000..63720f3c --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/pagers.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.recommendationengine_v1beta1.types import catalog +from google.cloud.recommendationengine_v1beta1.types import catalog_service + + +class ListCatalogItemsPager: + """A pager for iterating through ``list_catalog_items`` requests. + + This class thinly wraps an initial + :class:`google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``catalog_items`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCatalogItems`` requests and continue to iterate + through the ``catalog_items`` field on the + corresponding responses. + + All the usual :class:`google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsResponse` + 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[..., catalog_service.ListCatalogItemsResponse], + request: catalog_service.ListCatalogItemsRequest, + response: catalog_service.ListCatalogItemsResponse, + *, + 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.recommendationengine_v1beta1.types.ListCatalogItemsRequest): + The initial request object. + response (google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsResponse): + 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 = catalog_service.ListCatalogItemsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[catalog_service.ListCatalogItemsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[catalog.CatalogItem]: + for page in self.pages: + yield from page.catalog_items + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCatalogItemsAsyncPager: + """A pager for iterating through ``list_catalog_items`` requests. + + This class thinly wraps an initial + :class:`google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``catalog_items`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCatalogItems`` requests and continue to iterate + through the ``catalog_items`` field on the + corresponding responses. + + All the usual :class:`google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsResponse` + 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[catalog_service.ListCatalogItemsResponse]], + request: catalog_service.ListCatalogItemsRequest, + response: catalog_service.ListCatalogItemsResponse, + *, + 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.recommendationengine_v1beta1.types.ListCatalogItemsRequest): + The initial request object. + response (google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsResponse): + 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 = catalog_service.ListCatalogItemsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[catalog_service.ListCatalogItemsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[catalog.CatalogItem]: + async def async_generator(): + async for page in self.pages: + for response in page.catalog_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/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/__init__.py new file mode 100644 index 00000000..7d55f7e9 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import CatalogServiceTransport +from .grpc import CatalogServiceGrpcTransport +from .grpc_asyncio import CatalogServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CatalogServiceTransport]] +_transport_registry['grpc'] = CatalogServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CatalogServiceGrpcAsyncIOTransport + +__all__ = ( + 'CatalogServiceTransport', + 'CatalogServiceGrpcTransport', + 'CatalogServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/base.py new file mode 100644 index 00000000..f1d829ed --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/base.py @@ -0,0 +1,290 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.recommendationengine_v1beta1.types import catalog +from google.cloud.recommendationengine_v1beta1.types import catalog_service +from google.cloud.recommendationengine_v1beta1.types import import_ +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-recommendations-ai', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class CatalogServiceTransport(abc.ABC): + """Abstract transport class for CatalogService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'recommendationengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials is service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_catalog_item: gapic_v1.method.wrap_method( + self.create_catalog_item, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_catalog_item: gapic_v1.method.wrap_method( + self.get_catalog_item, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_catalog_items: gapic_v1.method.wrap_method( + self.list_catalog_items, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.update_catalog_item: gapic_v1.method.wrap_method( + self.update_catalog_item, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.delete_catalog_item: gapic_v1.method.wrap_method( + self.delete_catalog_item, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.import_catalog_items: gapic_v1.method.wrap_method( + self.import_catalog_items, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_catalog_item(self) -> Callable[ + [catalog_service.CreateCatalogItemRequest], + Union[ + catalog.CatalogItem, + Awaitable[catalog.CatalogItem] + ]]: + raise NotImplementedError() + + @property + def get_catalog_item(self) -> Callable[ + [catalog_service.GetCatalogItemRequest], + Union[ + catalog.CatalogItem, + Awaitable[catalog.CatalogItem] + ]]: + raise NotImplementedError() + + @property + def list_catalog_items(self) -> Callable[ + [catalog_service.ListCatalogItemsRequest], + Union[ + catalog_service.ListCatalogItemsResponse, + Awaitable[catalog_service.ListCatalogItemsResponse] + ]]: + raise NotImplementedError() + + @property + def update_catalog_item(self) -> Callable[ + [catalog_service.UpdateCatalogItemRequest], + Union[ + catalog.CatalogItem, + Awaitable[catalog.CatalogItem] + ]]: + raise NotImplementedError() + + @property + def delete_catalog_item(self) -> Callable[ + [catalog_service.DeleteCatalogItemRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def import_catalog_items(self) -> Callable[ + [import_.ImportCatalogItemsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'CatalogServiceTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc.py new file mode 100644 index 00000000..46efec81 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc.py @@ -0,0 +1,412 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.recommendationengine_v1beta1.types import catalog +from google.cloud.recommendationengine_v1beta1.types import catalog_service +from google.cloud.recommendationengine_v1beta1.types import import_ +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO + + +class CatalogServiceGrpcTransport(CatalogServiceTransport): + """gRPC backend transport for CatalogService. + + Service for ingesting catalog information of the customer's + website. + + 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 = 'recommendationengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'recommendationengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_catalog_item(self) -> Callable[ + [catalog_service.CreateCatalogItemRequest], + catalog.CatalogItem]: + r"""Return a callable for the create catalog item method over gRPC. + + Creates a catalog item. + + Returns: + Callable[[~.CreateCatalogItemRequest], + ~.CatalogItem]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog_item' not in self._stubs: + self._stubs['create_catalog_item'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.CatalogService/CreateCatalogItem', + request_serializer=catalog_service.CreateCatalogItemRequest.serialize, + response_deserializer=catalog.CatalogItem.deserialize, + ) + return self._stubs['create_catalog_item'] + + @property + def get_catalog_item(self) -> Callable[ + [catalog_service.GetCatalogItemRequest], + catalog.CatalogItem]: + r"""Return a callable for the get catalog item method over gRPC. + + Gets a specific catalog item. + + Returns: + Callable[[~.GetCatalogItemRequest], + ~.CatalogItem]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog_item' not in self._stubs: + self._stubs['get_catalog_item'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.CatalogService/GetCatalogItem', + request_serializer=catalog_service.GetCatalogItemRequest.serialize, + response_deserializer=catalog.CatalogItem.deserialize, + ) + return self._stubs['get_catalog_item'] + + @property + def list_catalog_items(self) -> Callable[ + [catalog_service.ListCatalogItemsRequest], + catalog_service.ListCatalogItemsResponse]: + r"""Return a callable for the list catalog items method over gRPC. + + Gets a list of catalog items. + + Returns: + Callable[[~.ListCatalogItemsRequest], + ~.ListCatalogItemsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog_items' not in self._stubs: + self._stubs['list_catalog_items'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.CatalogService/ListCatalogItems', + request_serializer=catalog_service.ListCatalogItemsRequest.serialize, + response_deserializer=catalog_service.ListCatalogItemsResponse.deserialize, + ) + return self._stubs['list_catalog_items'] + + @property + def update_catalog_item(self) -> Callable[ + [catalog_service.UpdateCatalogItemRequest], + catalog.CatalogItem]: + r"""Return a callable for the update catalog item method over gRPC. + + Updates a catalog item. Partial updating is + supported. Non-existing items will be created. + + Returns: + Callable[[~.UpdateCatalogItemRequest], + ~.CatalogItem]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog_item' not in self._stubs: + self._stubs['update_catalog_item'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.CatalogService/UpdateCatalogItem', + request_serializer=catalog_service.UpdateCatalogItemRequest.serialize, + response_deserializer=catalog.CatalogItem.deserialize, + ) + return self._stubs['update_catalog_item'] + + @property + def delete_catalog_item(self) -> Callable[ + [catalog_service.DeleteCatalogItemRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete catalog item method over gRPC. + + Deletes a catalog item. + + Returns: + Callable[[~.DeleteCatalogItemRequest], + ~.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_catalog_item' not in self._stubs: + self._stubs['delete_catalog_item'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.CatalogService/DeleteCatalogItem', + request_serializer=catalog_service.DeleteCatalogItemRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_catalog_item'] + + @property + def import_catalog_items(self) -> Callable[ + [import_.ImportCatalogItemsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import catalog items method over gRPC. + + Bulk import of multiple catalog items. Request + processing may be synchronous. No partial updating + supported. Non-existing items will be created. + + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully updated. + + Returns: + Callable[[~.ImportCatalogItemsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog_items' not in self._stubs: + self._stubs['import_catalog_items'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.CatalogService/ImportCatalogItems', + request_serializer=import_.ImportCatalogItemsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_catalog_items'] + + +__all__ = ( + 'CatalogServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..b5e6eba1 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc_asyncio.py @@ -0,0 +1,416 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.recommendationengine_v1beta1.types import catalog +from google.cloud.recommendationengine_v1beta1.types import catalog_service +from google.cloud.recommendationengine_v1beta1.types import import_ +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CatalogServiceGrpcTransport + + +class CatalogServiceGrpcAsyncIOTransport(CatalogServiceTransport): + """gRPC AsyncIO backend transport for CatalogService. + + Service for ingesting catalog information of the customer's + website. + + 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 = 'recommendationengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'recommendationengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_catalog_item(self) -> Callable[ + [catalog_service.CreateCatalogItemRequest], + Awaitable[catalog.CatalogItem]]: + r"""Return a callable for the create catalog item method over gRPC. + + Creates a catalog item. + + Returns: + Callable[[~.CreateCatalogItemRequest], + Awaitable[~.CatalogItem]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog_item' not in self._stubs: + self._stubs['create_catalog_item'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.CatalogService/CreateCatalogItem', + request_serializer=catalog_service.CreateCatalogItemRequest.serialize, + response_deserializer=catalog.CatalogItem.deserialize, + ) + return self._stubs['create_catalog_item'] + + @property + def get_catalog_item(self) -> Callable[ + [catalog_service.GetCatalogItemRequest], + Awaitable[catalog.CatalogItem]]: + r"""Return a callable for the get catalog item method over gRPC. + + Gets a specific catalog item. + + Returns: + Callable[[~.GetCatalogItemRequest], + Awaitable[~.CatalogItem]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog_item' not in self._stubs: + self._stubs['get_catalog_item'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.CatalogService/GetCatalogItem', + request_serializer=catalog_service.GetCatalogItemRequest.serialize, + response_deserializer=catalog.CatalogItem.deserialize, + ) + return self._stubs['get_catalog_item'] + + @property + def list_catalog_items(self) -> Callable[ + [catalog_service.ListCatalogItemsRequest], + Awaitable[catalog_service.ListCatalogItemsResponse]]: + r"""Return a callable for the list catalog items method over gRPC. + + Gets a list of catalog items. + + Returns: + Callable[[~.ListCatalogItemsRequest], + Awaitable[~.ListCatalogItemsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog_items' not in self._stubs: + self._stubs['list_catalog_items'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.CatalogService/ListCatalogItems', + request_serializer=catalog_service.ListCatalogItemsRequest.serialize, + response_deserializer=catalog_service.ListCatalogItemsResponse.deserialize, + ) + return self._stubs['list_catalog_items'] + + @property + def update_catalog_item(self) -> Callable[ + [catalog_service.UpdateCatalogItemRequest], + Awaitable[catalog.CatalogItem]]: + r"""Return a callable for the update catalog item method over gRPC. + + Updates a catalog item. Partial updating is + supported. Non-existing items will be created. + + Returns: + Callable[[~.UpdateCatalogItemRequest], + Awaitable[~.CatalogItem]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog_item' not in self._stubs: + self._stubs['update_catalog_item'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.CatalogService/UpdateCatalogItem', + request_serializer=catalog_service.UpdateCatalogItemRequest.serialize, + response_deserializer=catalog.CatalogItem.deserialize, + ) + return self._stubs['update_catalog_item'] + + @property + def delete_catalog_item(self) -> Callable[ + [catalog_service.DeleteCatalogItemRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete catalog item method over gRPC. + + Deletes a catalog item. + + Returns: + Callable[[~.DeleteCatalogItemRequest], + 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_catalog_item' not in self._stubs: + self._stubs['delete_catalog_item'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.CatalogService/DeleteCatalogItem', + request_serializer=catalog_service.DeleteCatalogItemRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_catalog_item'] + + @property + def import_catalog_items(self) -> Callable[ + [import_.ImportCatalogItemsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import catalog items method over gRPC. + + Bulk import of multiple catalog items. Request + processing may be synchronous. No partial updating + supported. Non-existing items will be created. + + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully updated. + + Returns: + Callable[[~.ImportCatalogItemsRequest], + 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_catalog_items' not in self._stubs: + self._stubs['import_catalog_items'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.CatalogService/ImportCatalogItems', + request_serializer=import_.ImportCatalogItemsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_catalog_items'] + + +__all__ = ( + 'CatalogServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/__init__.py new file mode 100644 index 00000000..d9500520 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import PredictionApiKeyRegistryClient +from .async_client import PredictionApiKeyRegistryAsyncClient + +__all__ = ( + 'PredictionApiKeyRegistryClient', + 'PredictionApiKeyRegistryAsyncClient', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/async_client.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/async_client.py new file mode 100644 index 00000000..702b4a01 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/async_client.py @@ -0,0 +1,430 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry import pagers +from google.cloud.recommendationengine_v1beta1.types import prediction_apikey_registry_service +from .transports.base import PredictionApiKeyRegistryTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import PredictionApiKeyRegistryGrpcAsyncIOTransport +from .client import PredictionApiKeyRegistryClient + + +class PredictionApiKeyRegistryAsyncClient: + """Service for registering API keys for use with the ``predict`` + method. If you use an API key to request predictions, you must first + register the API key. Otherwise, your prediction request is + rejected. If you use OAuth to authenticate your ``predict`` method + call, you do not need to register an API key. You can register up to + 20 API keys per project. + """ + + _client: PredictionApiKeyRegistryClient + + DEFAULT_ENDPOINT = PredictionApiKeyRegistryClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PredictionApiKeyRegistryClient.DEFAULT_MTLS_ENDPOINT + + event_store_path = staticmethod(PredictionApiKeyRegistryClient.event_store_path) + parse_event_store_path = staticmethod(PredictionApiKeyRegistryClient.parse_event_store_path) + prediction_api_key_registration_path = staticmethod(PredictionApiKeyRegistryClient.prediction_api_key_registration_path) + parse_prediction_api_key_registration_path = staticmethod(PredictionApiKeyRegistryClient.parse_prediction_api_key_registration_path) + common_billing_account_path = staticmethod(PredictionApiKeyRegistryClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(PredictionApiKeyRegistryClient.parse_common_billing_account_path) + common_folder_path = staticmethod(PredictionApiKeyRegistryClient.common_folder_path) + parse_common_folder_path = staticmethod(PredictionApiKeyRegistryClient.parse_common_folder_path) + common_organization_path = staticmethod(PredictionApiKeyRegistryClient.common_organization_path) + parse_common_organization_path = staticmethod(PredictionApiKeyRegistryClient.parse_common_organization_path) + common_project_path = staticmethod(PredictionApiKeyRegistryClient.common_project_path) + parse_common_project_path = staticmethod(PredictionApiKeyRegistryClient.parse_common_project_path) + common_location_path = staticmethod(PredictionApiKeyRegistryClient.common_location_path) + parse_common_location_path = staticmethod(PredictionApiKeyRegistryClient.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: + PredictionApiKeyRegistryAsyncClient: The constructed client. + """ + return PredictionApiKeyRegistryClient.from_service_account_info.__func__(PredictionApiKeyRegistryAsyncClient, 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: + PredictionApiKeyRegistryAsyncClient: The constructed client. + """ + return PredictionApiKeyRegistryClient.from_service_account_file.__func__(PredictionApiKeyRegistryAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> PredictionApiKeyRegistryTransport: + """Returns the transport used by the client instance. + + Returns: + PredictionApiKeyRegistryTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(PredictionApiKeyRegistryClient).get_transport_class, type(PredictionApiKeyRegistryClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, PredictionApiKeyRegistryTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the prediction api key registry client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.PredictionApiKeyRegistryTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = PredictionApiKeyRegistryClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_prediction_api_key_registration(self, + request: prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest = None, + *, + parent: str = None, + prediction_api_key_registration: prediction_apikey_registry_service.PredictionApiKeyRegistration = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> prediction_apikey_registry_service.PredictionApiKeyRegistration: + r"""Register an API key for use with predict method. + + Args: + request (:class:`google.cloud.recommendationengine_v1beta1.types.CreatePredictionApiKeyRegistrationRequest`): + The request object. Request message for the + `CreatePredictionApiKeyRegistration` method. + parent (:class:`str`): + Required. The parent resource path. + ``projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + prediction_api_key_registration (:class:`google.cloud.recommendationengine_v1beta1.types.PredictionApiKeyRegistration`): + Required. The prediction API key + registration. + + This corresponds to the ``prediction_api_key_registration`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recommendationengine_v1beta1.types.PredictionApiKeyRegistration: + Registered Api Key. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, prediction_api_key_registration]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if prediction_api_key_registration is not None: + request.prediction_api_key_registration = prediction_api_key_registration + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_prediction_api_key_registration, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_prediction_api_key_registrations(self, + request: prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPredictionApiKeyRegistrationsAsyncPager: + r"""List the registered apiKeys for use with predict + method. + + Args: + request (:class:`google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsRequest`): + The request object. Request message for the + `ListPredictionApiKeyRegistrations`. + parent (:class:`str`): + Required. The parent placement resource name such as + ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store`` + + 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.recommendationengine_v1beta1.services.prediction_api_key_registry.pagers.ListPredictionApiKeyRegistrationsAsyncPager: + Response message for the + ListPredictionApiKeyRegistrations. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_prediction_api_key_registrations, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListPredictionApiKeyRegistrationsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_prediction_api_key_registration(self, + request: prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Unregister an apiKey from using for predict method. + + Args: + request (:class:`google.cloud.recommendationengine_v1beta1.types.DeletePredictionApiKeyRegistrationRequest`): + The request object. Request message for + `DeletePredictionApiKeyRegistration` method. + name (:class:`str`): + Required. The API key to unregister including full + resource path. + ``projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_prediction_api_key_registration, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-recommendations-ai", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PredictionApiKeyRegistryAsyncClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/client.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/client.py new file mode 100644 index 00000000..cbe8c657 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/client.py @@ -0,0 +1,605 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry import pagers +from google.cloud.recommendationengine_v1beta1.types import prediction_apikey_registry_service +from .transports.base import PredictionApiKeyRegistryTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import PredictionApiKeyRegistryGrpcTransport +from .transports.grpc_asyncio import PredictionApiKeyRegistryGrpcAsyncIOTransport + + +class PredictionApiKeyRegistryClientMeta(type): + """Metaclass for the PredictionApiKeyRegistry 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[PredictionApiKeyRegistryTransport]] + _transport_registry["grpc"] = PredictionApiKeyRegistryGrpcTransport + _transport_registry["grpc_asyncio"] = PredictionApiKeyRegistryGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[PredictionApiKeyRegistryTransport]: + """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 PredictionApiKeyRegistryClient(metaclass=PredictionApiKeyRegistryClientMeta): + """Service for registering API keys for use with the ``predict`` + method. If you use an API key to request predictions, you must first + register the API key. Otherwise, your prediction request is + rejected. If you use OAuth to authenticate your ``predict`` method + call, you do not need to register an API key. You can register up to + 20 API keys per project. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "recommendationengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PredictionApiKeyRegistryClient: 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: + PredictionApiKeyRegistryClient: 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) -> PredictionApiKeyRegistryTransport: + """Returns the transport used by the client instance. + + Returns: + PredictionApiKeyRegistryTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def event_store_path(project: str,location: str,catalog: str,event_store: str,) -> str: + """Returns a fully-qualified event_store string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}".format(project=project, location=location, catalog=catalog, event_store=event_store, ) + + @staticmethod + def parse_event_store_path(path: str) -> Dict[str,str]: + """Parses a event_store path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/eventStores/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def prediction_api_key_registration_path(project: str,location: str,catalog: str,event_store: str,prediction_api_key_registration: str,) -> str: + """Returns a fully-qualified prediction_api_key_registration string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}/predictionApiKeyRegistrations/{prediction_api_key_registration}".format(project=project, location=location, catalog=catalog, event_store=event_store, prediction_api_key_registration=prediction_api_key_registration, ) + + @staticmethod + def parse_prediction_api_key_registration_path(path: str) -> Dict[str,str]: + """Parses a prediction_api_key_registration path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/eventStores/(?P.+?)/predictionApiKeyRegistrations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, PredictionApiKeyRegistryTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the prediction api key registry client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, PredictionApiKeyRegistryTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, PredictionApiKeyRegistryTransport): + # transport is a PredictionApiKeyRegistryTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def create_prediction_api_key_registration(self, + request: prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest = None, + *, + parent: str = None, + prediction_api_key_registration: prediction_apikey_registry_service.PredictionApiKeyRegistration = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> prediction_apikey_registry_service.PredictionApiKeyRegistration: + r"""Register an API key for use with predict method. + + Args: + request (google.cloud.recommendationengine_v1beta1.types.CreatePredictionApiKeyRegistrationRequest): + The request object. Request message for the + `CreatePredictionApiKeyRegistration` method. + parent (str): + Required. The parent resource path. + ``projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + prediction_api_key_registration (google.cloud.recommendationengine_v1beta1.types.PredictionApiKeyRegistration): + Required. The prediction API key + registration. + + This corresponds to the ``prediction_api_key_registration`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recommendationengine_v1beta1.types.PredictionApiKeyRegistration: + Registered Api Key. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, prediction_api_key_registration]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest): + request = prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if prediction_api_key_registration is not None: + request.prediction_api_key_registration = prediction_api_key_registration + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_prediction_api_key_registration] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_prediction_api_key_registrations(self, + request: prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPredictionApiKeyRegistrationsPager: + r"""List the registered apiKeys for use with predict + method. + + Args: + request (google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsRequest): + The request object. Request message for the + `ListPredictionApiKeyRegistrations`. + parent (str): + Required. The parent placement resource name such as + ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store`` + + 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.recommendationengine_v1beta1.services.prediction_api_key_registry.pagers.ListPredictionApiKeyRegistrationsPager: + Response message for the + ListPredictionApiKeyRegistrations. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest): + request = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest(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_prediction_api_key_registrations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListPredictionApiKeyRegistrationsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_prediction_api_key_registration(self, + request: prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Unregister an apiKey from using for predict method. + + Args: + request (google.cloud.recommendationengine_v1beta1.types.DeletePredictionApiKeyRegistrationRequest): + The request object. Request message for + `DeletePredictionApiKeyRegistration` method. + name (str): + Required. The API key to unregister including full + resource path. + ``projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest): + request = prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest(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_prediction_api_key_registration] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-recommendations-ai", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PredictionApiKeyRegistryClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/pagers.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/pagers.py new file mode 100644 index 00000000..e13086de --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.recommendationengine_v1beta1.types import prediction_apikey_registry_service + + +class ListPredictionApiKeyRegistrationsPager: + """A pager for iterating through ``list_prediction_api_key_registrations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``prediction_api_key_registrations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPredictionApiKeyRegistrations`` requests and continue to iterate + through the ``prediction_api_key_registrations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsResponse` + 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[..., prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse], + request: prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest, + response: prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse, + *, + 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.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsRequest): + The initial request object. + response (google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsResponse): + 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 = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[prediction_apikey_registry_service.PredictionApiKeyRegistration]: + for page in self.pages: + yield from page.prediction_api_key_registrations + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListPredictionApiKeyRegistrationsAsyncPager: + """A pager for iterating through ``list_prediction_api_key_registrations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``prediction_api_key_registrations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPredictionApiKeyRegistrations`` requests and continue to iterate + through the ``prediction_api_key_registrations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsResponse` + 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[prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse]], + request: prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest, + response: prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse, + *, + 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.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsRequest): + The initial request object. + response (google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsResponse): + 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 = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[prediction_apikey_registry_service.PredictionApiKeyRegistration]: + async def async_generator(): + async for page in self.pages: + for response in page.prediction_api_key_registrations: + 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/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/__init__.py new file mode 100644 index 00000000..af3443e5 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import PredictionApiKeyRegistryTransport +from .grpc import PredictionApiKeyRegistryGrpcTransport +from .grpc_asyncio import PredictionApiKeyRegistryGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PredictionApiKeyRegistryTransport]] +_transport_registry['grpc'] = PredictionApiKeyRegistryGrpcTransport +_transport_registry['grpc_asyncio'] = PredictionApiKeyRegistryGrpcAsyncIOTransport + +__all__ = ( + 'PredictionApiKeyRegistryTransport', + 'PredictionApiKeyRegistryGrpcTransport', + 'PredictionApiKeyRegistryGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/base.py new file mode 100644 index 00000000..daef5afd --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/base.py @@ -0,0 +1,218 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.recommendationengine_v1beta1.types import prediction_apikey_registry_service +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-recommendations-ai', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class PredictionApiKeyRegistryTransport(abc.ABC): + """Abstract transport class for PredictionApiKeyRegistry.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'recommendationengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials is service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_prediction_api_key_registration: gapic_v1.method.wrap_method( + self.create_prediction_api_key_registration, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_prediction_api_key_registrations: gapic_v1.method.wrap_method( + self.list_prediction_api_key_registrations, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.delete_prediction_api_key_registration: gapic_v1.method.wrap_method( + self.delete_prediction_api_key_registration, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + @property + def create_prediction_api_key_registration(self) -> Callable[ + [prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest], + Union[ + prediction_apikey_registry_service.PredictionApiKeyRegistration, + Awaitable[prediction_apikey_registry_service.PredictionApiKeyRegistration] + ]]: + raise NotImplementedError() + + @property + def list_prediction_api_key_registrations(self) -> Callable[ + [prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest], + Union[ + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse, + Awaitable[prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_prediction_api_key_registration(self) -> Callable[ + [prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'PredictionApiKeyRegistryTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc.py new file mode 100644 index 00000000..aa0feed7 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc.py @@ -0,0 +1,314 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.recommendationengine_v1beta1.types import prediction_apikey_registry_service +from google.protobuf import empty_pb2 # type: ignore +from .base import PredictionApiKeyRegistryTransport, DEFAULT_CLIENT_INFO + + +class PredictionApiKeyRegistryGrpcTransport(PredictionApiKeyRegistryTransport): + """gRPC backend transport for PredictionApiKeyRegistry. + + Service for registering API keys for use with the ``predict`` + method. If you use an API key to request predictions, you must first + register the API key. Otherwise, your prediction request is + rejected. If you use OAuth to authenticate your ``predict`` method + call, you do not need to register an API key. You can register up to + 20 API keys per project. + + 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 = 'recommendationengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'recommendationengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def create_prediction_api_key_registration(self) -> Callable[ + [prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest], + prediction_apikey_registry_service.PredictionApiKeyRegistration]: + r"""Return a callable for the create prediction api key + registration method over gRPC. + + Register an API key for use with predict method. + + Returns: + Callable[[~.CreatePredictionApiKeyRegistrationRequest], + ~.PredictionApiKeyRegistration]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_prediction_api_key_registration' not in self._stubs: + self._stubs['create_prediction_api_key_registration'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry/CreatePredictionApiKeyRegistration', + request_serializer=prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest.serialize, + response_deserializer=prediction_apikey_registry_service.PredictionApiKeyRegistration.deserialize, + ) + return self._stubs['create_prediction_api_key_registration'] + + @property + def list_prediction_api_key_registrations(self) -> Callable[ + [prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest], + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse]: + r"""Return a callable for the list prediction api key + registrations method over gRPC. + + List the registered apiKeys for use with predict + method. + + Returns: + Callable[[~.ListPredictionApiKeyRegistrationsRequest], + ~.ListPredictionApiKeyRegistrationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_prediction_api_key_registrations' not in self._stubs: + self._stubs['list_prediction_api_key_registrations'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry/ListPredictionApiKeyRegistrations', + request_serializer=prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest.serialize, + response_deserializer=prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse.deserialize, + ) + return self._stubs['list_prediction_api_key_registrations'] + + @property + def delete_prediction_api_key_registration(self) -> Callable[ + [prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete prediction api key + registration method over gRPC. + + Unregister an apiKey from using for predict method. + + Returns: + Callable[[~.DeletePredictionApiKeyRegistrationRequest], + ~.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_prediction_api_key_registration' not in self._stubs: + self._stubs['delete_prediction_api_key_registration'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry/DeletePredictionApiKeyRegistration', + request_serializer=prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_prediction_api_key_registration'] + + +__all__ = ( + 'PredictionApiKeyRegistryGrpcTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc_asyncio.py new file mode 100644 index 00000000..b00cf102 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc_asyncio.py @@ -0,0 +1,318 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.recommendationengine_v1beta1.types import prediction_apikey_registry_service +from google.protobuf import empty_pb2 # type: ignore +from .base import PredictionApiKeyRegistryTransport, DEFAULT_CLIENT_INFO +from .grpc import PredictionApiKeyRegistryGrpcTransport + + +class PredictionApiKeyRegistryGrpcAsyncIOTransport(PredictionApiKeyRegistryTransport): + """gRPC AsyncIO backend transport for PredictionApiKeyRegistry. + + Service for registering API keys for use with the ``predict`` + method. If you use an API key to request predictions, you must first + register the API key. Otherwise, your prediction request is + rejected. If you use OAuth to authenticate your ``predict`` method + call, you do not need to register an API key. You can register up to + 20 API keys per project. + + 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 = 'recommendationengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'recommendationengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_prediction_api_key_registration(self) -> Callable[ + [prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest], + Awaitable[prediction_apikey_registry_service.PredictionApiKeyRegistration]]: + r"""Return a callable for the create prediction api key + registration method over gRPC. + + Register an API key for use with predict method. + + Returns: + Callable[[~.CreatePredictionApiKeyRegistrationRequest], + Awaitable[~.PredictionApiKeyRegistration]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_prediction_api_key_registration' not in self._stubs: + self._stubs['create_prediction_api_key_registration'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry/CreatePredictionApiKeyRegistration', + request_serializer=prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest.serialize, + response_deserializer=prediction_apikey_registry_service.PredictionApiKeyRegistration.deserialize, + ) + return self._stubs['create_prediction_api_key_registration'] + + @property + def list_prediction_api_key_registrations(self) -> Callable[ + [prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest], + Awaitable[prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse]]: + r"""Return a callable for the list prediction api key + registrations method over gRPC. + + List the registered apiKeys for use with predict + method. + + Returns: + Callable[[~.ListPredictionApiKeyRegistrationsRequest], + Awaitable[~.ListPredictionApiKeyRegistrationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_prediction_api_key_registrations' not in self._stubs: + self._stubs['list_prediction_api_key_registrations'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry/ListPredictionApiKeyRegistrations', + request_serializer=prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest.serialize, + response_deserializer=prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse.deserialize, + ) + return self._stubs['list_prediction_api_key_registrations'] + + @property + def delete_prediction_api_key_registration(self) -> Callable[ + [prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete prediction api key + registration method over gRPC. + + Unregister an apiKey from using for predict method. + + Returns: + Callable[[~.DeletePredictionApiKeyRegistrationRequest], + 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_prediction_api_key_registration' not in self._stubs: + self._stubs['delete_prediction_api_key_registration'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry/DeletePredictionApiKeyRegistration', + request_serializer=prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_prediction_api_key_registration'] + + +__all__ = ( + 'PredictionApiKeyRegistryGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/__init__.py new file mode 100644 index 00000000..13c5d11c --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import PredictionServiceClient +from .async_client import PredictionServiceAsyncClient + +__all__ = ( + 'PredictionServiceClient', + 'PredictionServiceAsyncClient', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/async_client.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/async_client.py new file mode 100644 index 00000000..b200d750 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/async_client.py @@ -0,0 +1,310 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.recommendationengine_v1beta1.services.prediction_service import pagers +from google.cloud.recommendationengine_v1beta1.types import prediction_service +from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event +from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport +from .client import PredictionServiceClient + + +class PredictionServiceAsyncClient: + """Service for making recommendation prediction.""" + + _client: PredictionServiceClient + + DEFAULT_ENDPOINT = PredictionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PredictionServiceClient.DEFAULT_MTLS_ENDPOINT + + placement_path = staticmethod(PredictionServiceClient.placement_path) + parse_placement_path = staticmethod(PredictionServiceClient.parse_placement_path) + common_billing_account_path = staticmethod(PredictionServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(PredictionServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(PredictionServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(PredictionServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(PredictionServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(PredictionServiceClient.parse_common_organization_path) + common_project_path = staticmethod(PredictionServiceClient.common_project_path) + parse_common_project_path = staticmethod(PredictionServiceClient.parse_common_project_path) + common_location_path = staticmethod(PredictionServiceClient.common_location_path) + parse_common_location_path = staticmethod(PredictionServiceClient.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: + PredictionServiceAsyncClient: The constructed client. + """ + return PredictionServiceClient.from_service_account_info.__func__(PredictionServiceAsyncClient, 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: + PredictionServiceAsyncClient: The constructed client. + """ + return PredictionServiceClient.from_service_account_file.__func__(PredictionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> PredictionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + PredictionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(PredictionServiceClient).get_transport_class, type(PredictionServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, PredictionServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the prediction service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.PredictionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = PredictionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def predict(self, + request: prediction_service.PredictRequest = None, + *, + name: str = None, + user_event: gcr_user_event.UserEvent = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.PredictAsyncPager: + r"""Makes a recommendation prediction. If using API Key based + authentication, the API Key must be registered using the + [PredictionApiKeyRegistry][google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry] + service. `Learn + more `__. + + Args: + request (:class:`google.cloud.recommendationengine_v1beta1.types.PredictRequest`): + The request object. Request message for Predict method. + name (:class:`str`): + Required. Full resource name of the format: + ``{name=projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/placements/*}`` + The id of the recommendation engine placement. This id + is used to identify the set of models that will be used + to make the prediction. + + We currently support three placements with the following + IDs by default: + + - ``shopping_cart``: Predicts items frequently bought + together with one or more catalog items in the same + shopping session. Commonly displayed after + ``add-to-cart`` events, on product detail pages, or + on the shopping cart page. + + - ``home_page``: Predicts the next product that a user + will most likely engage with or purchase based on the + shopping or viewing history of the specified + ``userId`` or ``visitorId``. For example - + Recommendations for you. + + - ``product_detail``: Predicts the next product that a + user will most likely engage with or purchase. The + prediction is based on the shopping or viewing + history of the specified ``userId`` or ``visitorId`` + and its relevance to a specified ``CatalogItem``. + Typically used on product detail pages. For example - + More items like this. + + - ``recently_viewed_default``: Returns up to 75 items + recently viewed by the specified ``userId`` or + ``visitorId``, most recent ones first. Returns + nothing if neither of them has viewed any items yet. + For example - Recently viewed. + + The full list of available placements can be seen at + https://console.cloud.google.com/recommendation/datafeeds/default_catalog/dashboard + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_event (:class:`google.cloud.recommendationengine_v1beta1.types.UserEvent`): + Required. Context about the user, + what they are looking at and what action + they took to trigger the predict + request. Note that this user event + detail won't be ingested to userEvent + logs. Thus, a separate userEvent write + request is required for event logging. + + This corresponds to the ``user_event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recommendationengine_v1beta1.services.prediction_service.pagers.PredictAsyncPager: + Response message for predict method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, user_event]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = prediction_service.PredictRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if user_event is not None: + request.user_event = user_event + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.predict, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.PredictAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-recommendations-ai", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PredictionServiceAsyncClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/client.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/client.py new file mode 100644 index 00000000..3ad05964 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/client.py @@ -0,0 +1,490 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.recommendationengine_v1beta1.services.prediction_service import pagers +from google.cloud.recommendationengine_v1beta1.types import prediction_service +from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event +from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import PredictionServiceGrpcTransport +from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport + + +class PredictionServiceClientMeta(type): + """Metaclass for the PredictionService 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[PredictionServiceTransport]] + _transport_registry["grpc"] = PredictionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = PredictionServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[PredictionServiceTransport]: + """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 PredictionServiceClient(metaclass=PredictionServiceClientMeta): + """Service for making recommendation prediction.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "recommendationengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PredictionServiceClient: 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: + PredictionServiceClient: 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) -> PredictionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + PredictionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def placement_path(project: str,location: str,catalog: str,event_store: str,placement: str,) -> str: + """Returns a fully-qualified placement string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}/placements/{placement}".format(project=project, location=location, catalog=catalog, event_store=event_store, placement=placement, ) + + @staticmethod + def parse_placement_path(path: str) -> Dict[str,str]: + """Parses a placement path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/eventStores/(?P.+?)/placements/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, PredictionServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the prediction service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, PredictionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, PredictionServiceTransport): + # transport is a PredictionServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def predict(self, + request: prediction_service.PredictRequest = None, + *, + name: str = None, + user_event: gcr_user_event.UserEvent = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.PredictPager: + r"""Makes a recommendation prediction. If using API Key based + authentication, the API Key must be registered using the + [PredictionApiKeyRegistry][google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry] + service. `Learn + more `__. + + Args: + request (google.cloud.recommendationengine_v1beta1.types.PredictRequest): + The request object. Request message for Predict method. + name (str): + Required. Full resource name of the format: + ``{name=projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/placements/*}`` + The id of the recommendation engine placement. This id + is used to identify the set of models that will be used + to make the prediction. + + We currently support three placements with the following + IDs by default: + + - ``shopping_cart``: Predicts items frequently bought + together with one or more catalog items in the same + shopping session. Commonly displayed after + ``add-to-cart`` events, on product detail pages, or + on the shopping cart page. + + - ``home_page``: Predicts the next product that a user + will most likely engage with or purchase based on the + shopping or viewing history of the specified + ``userId`` or ``visitorId``. For example - + Recommendations for you. + + - ``product_detail``: Predicts the next product that a + user will most likely engage with or purchase. The + prediction is based on the shopping or viewing + history of the specified ``userId`` or ``visitorId`` + and its relevance to a specified ``CatalogItem``. + Typically used on product detail pages. For example - + More items like this. + + - ``recently_viewed_default``: Returns up to 75 items + recently viewed by the specified ``userId`` or + ``visitorId``, most recent ones first. Returns + nothing if neither of them has viewed any items yet. + For example - Recently viewed. + + The full list of available placements can be seen at + https://console.cloud.google.com/recommendation/datafeeds/default_catalog/dashboard + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_event (google.cloud.recommendationengine_v1beta1.types.UserEvent): + Required. Context about the user, + what they are looking at and what action + they took to trigger the predict + request. Note that this user event + detail won't be ingested to userEvent + logs. Thus, a separate userEvent write + request is required for event logging. + + This corresponds to the ``user_event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recommendationengine_v1beta1.services.prediction_service.pagers.PredictPager: + Response message for predict method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, user_event]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a prediction_service.PredictRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, prediction_service.PredictRequest): + request = prediction_service.PredictRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if user_event is not None: + request.user_event = user_event + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.predict] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.PredictPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-recommendations-ai", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PredictionServiceClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/pagers.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/pagers.py new file mode 100644 index 00000000..647d24c7 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.recommendationengine_v1beta1.types import prediction_service + + +class PredictPager: + """A pager for iterating through ``predict`` requests. + + This class thinly wraps an initial + :class:`google.cloud.recommendationengine_v1beta1.types.PredictResponse` object, and + provides an ``__iter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``Predict`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.recommendationengine_v1beta1.types.PredictResponse` + 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[..., prediction_service.PredictResponse], + request: prediction_service.PredictRequest, + response: prediction_service.PredictResponse, + *, + 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.recommendationengine_v1beta1.types.PredictRequest): + The initial request object. + response (google.cloud.recommendationengine_v1beta1.types.PredictResponse): + 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 = prediction_service.PredictRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[prediction_service.PredictResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[prediction_service.PredictResponse.PredictionResult]: + for page in self.pages: + yield from page.results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class PredictAsyncPager: + """A pager for iterating through ``predict`` requests. + + This class thinly wraps an initial + :class:`google.cloud.recommendationengine_v1beta1.types.PredictResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``Predict`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.recommendationengine_v1beta1.types.PredictResponse` + 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[prediction_service.PredictResponse]], + request: prediction_service.PredictRequest, + response: prediction_service.PredictResponse, + *, + 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.recommendationengine_v1beta1.types.PredictRequest): + The initial request object. + response (google.cloud.recommendationengine_v1beta1.types.PredictResponse): + 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 = prediction_service.PredictRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[prediction_service.PredictResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[prediction_service.PredictResponse.PredictionResult]: + async def async_generator(): + async for page in self.pages: + for response in page.results: + 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/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/__init__.py new file mode 100644 index 00000000..d747de2c --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import PredictionServiceTransport +from .grpc import PredictionServiceGrpcTransport +from .grpc_asyncio import PredictionServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PredictionServiceTransport]] +_transport_registry['grpc'] = PredictionServiceGrpcTransport +_transport_registry['grpc_asyncio'] = PredictionServiceGrpcAsyncIOTransport + +__all__ = ( + 'PredictionServiceTransport', + 'PredictionServiceGrpcTransport', + 'PredictionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/base.py new file mode 100644 index 00000000..342837c8 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/base.py @@ -0,0 +1,175 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.recommendationengine_v1beta1.types import prediction_service + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-recommendations-ai', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class PredictionServiceTransport(abc.ABC): + """Abstract transport class for PredictionService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'recommendationengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials is service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.predict: gapic_v1.method.wrap_method( + self.predict, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + @property + def predict(self) -> Callable[ + [prediction_service.PredictRequest], + Union[ + prediction_service.PredictResponse, + Awaitable[prediction_service.PredictResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'PredictionServiceTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc.py new file mode 100644 index 00000000..db4532e4 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc.py @@ -0,0 +1,256 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.recommendationengine_v1beta1.types import prediction_service +from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO + + +class PredictionServiceGrpcTransport(PredictionServiceTransport): + """gRPC backend transport for PredictionService. + + Service for making recommendation prediction. + + 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 = 'recommendationengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'recommendationengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def predict(self) -> Callable[ + [prediction_service.PredictRequest], + prediction_service.PredictResponse]: + r"""Return a callable for the predict method over gRPC. + + Makes a recommendation prediction. If using API Key based + authentication, the API Key must be registered using the + [PredictionApiKeyRegistry][google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry] + service. `Learn + more `__. + + Returns: + Callable[[~.PredictRequest], + ~.PredictResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'predict' not in self._stubs: + self._stubs['predict'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.PredictionService/Predict', + request_serializer=prediction_service.PredictRequest.serialize, + response_deserializer=prediction_service.PredictResponse.deserialize, + ) + return self._stubs['predict'] + + +__all__ = ( + 'PredictionServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..11bd3981 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc_asyncio.py @@ -0,0 +1,260 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.recommendationengine_v1beta1.types import prediction_service +from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import PredictionServiceGrpcTransport + + +class PredictionServiceGrpcAsyncIOTransport(PredictionServiceTransport): + """gRPC AsyncIO backend transport for PredictionService. + + Service for making recommendation prediction. + + 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 = 'recommendationengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'recommendationengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def predict(self) -> Callable[ + [prediction_service.PredictRequest], + Awaitable[prediction_service.PredictResponse]]: + r"""Return a callable for the predict method over gRPC. + + Makes a recommendation prediction. If using API Key based + authentication, the API Key must be registered using the + [PredictionApiKeyRegistry][google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry] + service. `Learn + more `__. + + Returns: + Callable[[~.PredictRequest], + Awaitable[~.PredictResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'predict' not in self._stubs: + self._stubs['predict'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.PredictionService/Predict', + request_serializer=prediction_service.PredictRequest.serialize, + response_deserializer=prediction_service.PredictResponse.deserialize, + ) + return self._stubs['predict'] + + +__all__ = ( + 'PredictionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/__init__.py new file mode 100644 index 00000000..808f8208 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import UserEventServiceClient +from .async_client import UserEventServiceAsyncClient + +__all__ = ( + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/async_client.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/async_client.py new file mode 100644 index 00000000..99491310 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/async_client.py @@ -0,0 +1,847 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.recommendationengine_v1beta1.services.user_event_service import pagers +from google.cloud.recommendationengine_v1beta1.types import import_ +from google.cloud.recommendationengine_v1beta1.types import user_event +from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event +from google.cloud.recommendationengine_v1beta1.types import user_event_service +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport +from .client import UserEventServiceClient + + +class UserEventServiceAsyncClient: + """Service for ingesting end user actions on the customer + website. + """ + + _client: UserEventServiceClient + + DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT + + event_store_path = staticmethod(UserEventServiceClient.event_store_path) + parse_event_store_path = staticmethod(UserEventServiceClient.parse_event_store_path) + common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) + common_project_path = staticmethod(UserEventServiceClient.common_project_path) + parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) + common_location_path = staticmethod(UserEventServiceClient.common_location_path) + parse_common_location_path = staticmethod(UserEventServiceClient.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: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, 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: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = UserEventServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def write_user_event(self, + request: user_event_service.WriteUserEventRequest = None, + *, + parent: str = None, + user_event: gcr_user_event.UserEvent = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_user_event.UserEvent: + r"""Writes a single user event. + + Args: + request (:class:`google.cloud.recommendationengine_v1beta1.types.WriteUserEventRequest`): + The request object. Request message for WriteUserEvent + method. + parent (:class:`str`): + Required. The parent eventStore resource name, such as + ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_event (:class:`google.cloud.recommendationengine_v1beta1.types.UserEvent`): + Required. User event to write. + This corresponds to the ``user_event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recommendationengine_v1beta1.types.UserEvent: + UserEvent captures all metadata + information recommendation engine needs + to know about how end users interact + with customers' website. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, user_event]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = user_event_service.WriteUserEventRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user_event is not None: + request.user_event = user_event + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.write_user_event, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def collect_user_event(self, + request: user_event_service.CollectUserEventRequest = None, + *, + parent: str = None, + user_event: str = None, + uri: str = None, + ets: int = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Recommendations AI + JavaScript pixel. Users should not call this method + directly. + + Args: + request (:class:`google.cloud.recommendationengine_v1beta1.types.CollectUserEventRequest`): + The request object. Request message for CollectUserEvent + method. + parent (:class:`str`): + Required. The parent eventStore name, such as + ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_event (:class:`str`): + Required. URL encoded UserEvent + proto. + + This corresponds to the ``user_event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + uri (:class:`str`): + Optional. The url including cgi- + arameters but excluding the hash + fragment. The URL must be truncated to + 1.5K bytes to conservatively be under + the 2K bytes. This is often more useful + than the referer url, because many + browsers only send the domain for 3rd + party requests. + + This corresponds to the ``uri`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ets (:class:`int`): + Optional. The event timestamp in + milliseconds. This prevents browser + caching of otherwise identical get + requests. The name is abbreviated to + reduce the payload bytes. + + This corresponds to the ``ets`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) returns + (google.api.HttpBody); rpc + UpdateResource(google.api.HttpBody) returns + (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, user_event, uri, ets]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = user_event_service.CollectUserEventRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user_event is not None: + request.user_event = user_event + if uri is not None: + request.uri = uri + if ets is not None: + request.ets = ets + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.collect_user_event, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_user_events(self, + request: user_event_service.ListUserEventsRequest = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListUserEventsAsyncPager: + r"""Gets a list of user events within a time range, with + potential filtering. + + Args: + request (:class:`google.cloud.recommendationengine_v1beta1.types.ListUserEventsRequest`): + The request object. Request message for ListUserEvents + method. + parent (:class:`str`): + Required. The parent eventStore resource name, such as + ``projects/*/locations/*/catalogs/default_catalog/eventStores/default_event_store``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Optional. Filtering expression to specify restrictions + over returned events. This is a sequence of terms, where + each term applies some kind of a restriction to the + returned user events. Use this expression to restrict + results to a specific time range, or filter events by + eventType. eg: eventTime > "2012-04-23T18:25:43.511Z" + eventsMissingCatalogItems + eventTime<"2012-04-23T18:25:43.511Z" eventType=search + + We expect only 3 types of fields: + + :: + + * eventTime: this can be specified a maximum of 2 times, once with a + less than operator and once with a greater than operator. The + eventTime restrict should result in one contiguous valid eventTime + range. + + * eventType: only 1 eventType restriction can be specified. + + * eventsMissingCatalogItems: specififying this will restrict results + to events for which catalog items were not found in the catalog. The + default behavior is to return only those events for which catalog + items were found. + + Some examples of valid filters expressions: + + - Example 1: eventTime > "2012-04-23T18:25:43.511Z" + eventTime < "2012-04-23T18:30:43.511Z" + - Example 2: eventTime > "2012-04-23T18:25:43.511Z" + eventType = detail-page-view + - Example 3: eventsMissingCatalogItems eventType = + search eventTime < "2018-04-23T18:30:43.511Z" + - Example 4: eventTime > "2012-04-23T18:25:43.511Z" + - Example 5: eventType = search + - Example 6: eventsMissingCatalogItems + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recommendationengine_v1beta1.services.user_event_service.pagers.ListUserEventsAsyncPager: + Response message for ListUserEvents + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, filter]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = user_event_service.ListUserEventsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListUserEventsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def purge_user_events(self, + request: user_event_service.PurgeUserEventsRequest = None, + *, + parent: str = None, + filter: str = None, + force: bool = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + Args: + request (:class:`google.cloud.recommendationengine_v1beta1.types.PurgeUserEventsRequest`): + The request object. Request message for PurgeUserEvents + method. + parent (:class:`str`): + Required. The resource name of the event_store under + which the events are created. The format is + ``projects/${projectId}/locations/global/catalogs/${catalogId}/eventStores/${eventStoreId}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Required. The filter string to specify the events to be + deleted. Empty string filter is not allowed. This filter + can also be used with ListUserEvents API to list events + that will be deleted. The eligible fields for filtering + are: + + - eventType - UserEvent.eventType field of type string. + - eventTime - in ISO 8601 "zulu" format. + - visitorId - field of type string. Specifying this + will delete all events associated with a visitor. + - userId - field of type string. Specifying this will + delete all events associated with a user. Example 1: + Deleting all events in a time range. + ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` + Example 2: Deleting specific eventType in time range. + ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` + Example 3: Deleting all events for a specific visitor + ``visitorId = visitor1024`` The filtering fields are + assumed to have an implicit AND. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + force (:class:`bool`): + Optional. The default value is false. + Override this flag to true to actually + perform the purge. If the field is not + set to true, a sampling of events to be + deleted will be returned. + + This corresponds to the ``force`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.recommendationengine_v1beta1.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, filter, force]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = user_event_service.PurgeUserEventsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + if force is not None: + request.force = force + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.purge_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + user_event_service.PurgeUserEventsResponse, + metadata_type=user_event_service.PurgeUserEventsMetadata, + ) + + # Done; return the response. + return response + + async def import_user_events(self, + request: import_.ImportUserEventsRequest = None, + *, + parent: str = None, + request_id: str = None, + input_config: import_.InputConfig = None, + errors_config: import_.ImportErrorsConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Args: + request (:class:`google.cloud.recommendationengine_v1beta1.types.ImportUserEventsRequest`): + The request object. Request message for the + ImportUserEvents request. + parent (:class:`str`): + Required. + ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + request_id (:class:`str`): + Optional. Unique identifier provided by client, within + the ancestor dataset scope. Ensures idempotency for + expensive long running operations. Server-generated if + unspecified. Up to 128 characters long. This is returned + as google.longrunning.Operation.name in the response. + Note that this field must not be set if the desired + input config is catalog_inline_source. + + This corresponds to the ``request_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + input_config (:class:`google.cloud.recommendationengine_v1beta1.types.InputConfig`): + Required. The desired input location + of the data. + + This corresponds to the ``input_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + errors_config (:class:`google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig`): + Optional. The desired location of + errors incurred during the Import. + + This corresponds to the ``errors_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.recommendationengine_v1beta1.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, request_id, input_config, errors_config]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = import_.ImportUserEventsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if request_id is not None: + request.request_id = request_id + if input_config is not None: + request.input_config = input_config + if errors_config is not None: + request.errors_config = errors_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_.ImportUserEventsResponse, + metadata_type=import_.ImportMetadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-recommendations-ai", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "UserEventServiceAsyncClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/client.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/client.py new file mode 100644 index 00000000..c3575cb3 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/client.py @@ -0,0 +1,999 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.recommendationengine_v1beta1.services.user_event_service import pagers +from google.cloud.recommendationengine_v1beta1.types import import_ +from google.cloud.recommendationengine_v1beta1.types import user_event +from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event +from google.cloud.recommendationengine_v1beta1.types import user_event_service +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import UserEventServiceGrpcTransport +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport + + +class UserEventServiceClientMeta(type): + """Metaclass for the UserEventService 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[UserEventServiceTransport]] + _transport_registry["grpc"] = UserEventServiceGrpcTransport + _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[UserEventServiceTransport]: + """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 UserEventServiceClient(metaclass=UserEventServiceClientMeta): + """Service for ingesting end user actions on the customer + website. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "recommendationengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceClient: 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: + UserEventServiceClient: 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) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def event_store_path(project: str,location: str,catalog: str,event_store: str,) -> str: + """Returns a fully-qualified event_store string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}".format(project=project, location=location, catalog=catalog, event_store=event_store, ) + + @staticmethod + def parse_event_store_path(path: str) -> Dict[str,str]: + """Parses a event_store path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/eventStores/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, UserEventServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, UserEventServiceTransport): + # transport is a UserEventServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def write_user_event(self, + request: user_event_service.WriteUserEventRequest = None, + *, + parent: str = None, + user_event: gcr_user_event.UserEvent = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_user_event.UserEvent: + r"""Writes a single user event. + + Args: + request (google.cloud.recommendationengine_v1beta1.types.WriteUserEventRequest): + The request object. Request message for WriteUserEvent + method. + parent (str): + Required. The parent eventStore resource name, such as + ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_event (google.cloud.recommendationengine_v1beta1.types.UserEvent): + Required. User event to write. + This corresponds to the ``user_event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recommendationengine_v1beta1.types.UserEvent: + UserEvent captures all metadata + information recommendation engine needs + to know about how end users interact + with customers' website. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, user_event]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.WriteUserEventRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.WriteUserEventRequest): + request = user_event_service.WriteUserEventRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user_event is not None: + request.user_event = user_event + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.write_user_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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def collect_user_event(self, + request: user_event_service.CollectUserEventRequest = None, + *, + parent: str = None, + user_event: str = None, + uri: str = None, + ets: int = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Recommendations AI + JavaScript pixel. Users should not call this method + directly. + + Args: + request (google.cloud.recommendationengine_v1beta1.types.CollectUserEventRequest): + The request object. Request message for CollectUserEvent + method. + parent (str): + Required. The parent eventStore name, such as + ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_event (str): + Required. URL encoded UserEvent + proto. + + This corresponds to the ``user_event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + uri (str): + Optional. The url including cgi- + arameters but excluding the hash + fragment. The URL must be truncated to + 1.5K bytes to conservatively be under + the 2K bytes. This is often more useful + than the referer url, because many + browsers only send the domain for 3rd + party requests. + + This corresponds to the ``uri`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ets (int): + Optional. The event timestamp in + milliseconds. This prevents browser + caching of otherwise identical get + requests. The name is abbreviated to + reduce the payload bytes. + + This corresponds to the ``ets`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) returns + (google.api.HttpBody); rpc + UpdateResource(google.api.HttpBody) returns + (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, user_event, uri, ets]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.CollectUserEventRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.CollectUserEventRequest): + request = user_event_service.CollectUserEventRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user_event is not None: + request.user_event = user_event + if uri is not None: + request.uri = uri + if ets is not None: + request.ets = ets + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.collect_user_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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_user_events(self, + request: user_event_service.ListUserEventsRequest = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListUserEventsPager: + r"""Gets a list of user events within a time range, with + potential filtering. + + Args: + request (google.cloud.recommendationengine_v1beta1.types.ListUserEventsRequest): + The request object. Request message for ListUserEvents + method. + parent (str): + Required. The parent eventStore resource name, such as + ``projects/*/locations/*/catalogs/default_catalog/eventStores/default_event_store``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + Optional. Filtering expression to specify restrictions + over returned events. This is a sequence of terms, where + each term applies some kind of a restriction to the + returned user events. Use this expression to restrict + results to a specific time range, or filter events by + eventType. eg: eventTime > "2012-04-23T18:25:43.511Z" + eventsMissingCatalogItems + eventTime<"2012-04-23T18:25:43.511Z" eventType=search + + We expect only 3 types of fields: + + :: + + * eventTime: this can be specified a maximum of 2 times, once with a + less than operator and once with a greater than operator. The + eventTime restrict should result in one contiguous valid eventTime + range. + + * eventType: only 1 eventType restriction can be specified. + + * eventsMissingCatalogItems: specififying this will restrict results + to events for which catalog items were not found in the catalog. The + default behavior is to return only those events for which catalog + items were found. + + Some examples of valid filters expressions: + + - Example 1: eventTime > "2012-04-23T18:25:43.511Z" + eventTime < "2012-04-23T18:30:43.511Z" + - Example 2: eventTime > "2012-04-23T18:25:43.511Z" + eventType = detail-page-view + - Example 3: eventsMissingCatalogItems eventType = + search eventTime < "2018-04-23T18:30:43.511Z" + - Example 4: eventTime > "2012-04-23T18:25:43.511Z" + - Example 5: eventType = search + - Example 6: eventsMissingCatalogItems + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recommendationengine_v1beta1.services.user_event_service.pagers.ListUserEventsPager: + Response message for ListUserEvents + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, filter]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.ListUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.ListUserEventsRequest): + request = user_event_service.ListUserEventsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_user_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), + )), + ) + + # 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.ListUserEventsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def purge_user_events(self, + request: user_event_service.PurgeUserEventsRequest = None, + *, + parent: str = None, + filter: str = None, + force: bool = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + Args: + request (google.cloud.recommendationengine_v1beta1.types.PurgeUserEventsRequest): + The request object. Request message for PurgeUserEvents + method. + parent (str): + Required. The resource name of the event_store under + which the events are created. The format is + ``projects/${projectId}/locations/global/catalogs/${catalogId}/eventStores/${eventStoreId}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + Required. The filter string to specify the events to be + deleted. Empty string filter is not allowed. This filter + can also be used with ListUserEvents API to list events + that will be deleted. The eligible fields for filtering + are: + + - eventType - UserEvent.eventType field of type string. + - eventTime - in ISO 8601 "zulu" format. + - visitorId - field of type string. Specifying this + will delete all events associated with a visitor. + - userId - field of type string. Specifying this will + delete all events associated with a user. Example 1: + Deleting all events in a time range. + ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` + Example 2: Deleting specific eventType in time range. + ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` + Example 3: Deleting all events for a specific visitor + ``visitorId = visitor1024`` The filtering fields are + assumed to have an implicit AND. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + force (bool): + Optional. The default value is false. + Override this flag to true to actually + perform the purge. If the field is not + set to true, a sampling of events to be + deleted will be returned. + + This corresponds to the ``force`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.recommendationengine_v1beta1.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, filter, force]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.PurgeUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.PurgeUserEventsRequest): + request = user_event_service.PurgeUserEventsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + if force is not None: + request.force = force + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.purge_user_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), + )), + ) + + # 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, + user_event_service.PurgeUserEventsResponse, + metadata_type=user_event_service.PurgeUserEventsMetadata, + ) + + # Done; return the response. + return response + + def import_user_events(self, + request: import_.ImportUserEventsRequest = None, + *, + parent: str = None, + request_id: str = None, + input_config: import_.InputConfig = None, + errors_config: import_.ImportErrorsConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Args: + request (google.cloud.recommendationengine_v1beta1.types.ImportUserEventsRequest): + The request object. Request message for the + ImportUserEvents request. + parent (str): + Required. + ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + request_id (str): + Optional. Unique identifier provided by client, within + the ancestor dataset scope. Ensures idempotency for + expensive long running operations. Server-generated if + unspecified. Up to 128 characters long. This is returned + as google.longrunning.Operation.name in the response. + Note that this field must not be set if the desired + input config is catalog_inline_source. + + This corresponds to the ``request_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + input_config (google.cloud.recommendationengine_v1beta1.types.InputConfig): + Required. The desired input location + of the data. + + This corresponds to the ``input_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + errors_config (google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig): + Optional. The desired location of + errors incurred during the Import. + + This corresponds to the ``errors_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.recommendationengine_v1beta1.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, request_id, input_config, errors_config]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a import_.ImportUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_.ImportUserEventsRequest): + request = import_.ImportUserEventsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if request_id is not None: + request.request_id = request_id + if input_config is not None: + request.input_config = input_config + if errors_config is not None: + request.errors_config = errors_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_user_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), + )), + ) + + # 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, + import_.ImportUserEventsResponse, + metadata_type=import_.ImportMetadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-recommendations-ai", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "UserEventServiceClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/pagers.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/pagers.py new file mode 100644 index 00000000..bea00988 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/pagers.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.recommendationengine_v1beta1.types import user_event +from google.cloud.recommendationengine_v1beta1.types import user_event_service + + +class ListUserEventsPager: + """A pager for iterating through ``list_user_events`` requests. + + This class thinly wraps an initial + :class:`google.cloud.recommendationengine_v1beta1.types.ListUserEventsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``user_events`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListUserEvents`` requests and continue to iterate + through the ``user_events`` field on the + corresponding responses. + + All the usual :class:`google.cloud.recommendationengine_v1beta1.types.ListUserEventsResponse` + 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[..., user_event_service.ListUserEventsResponse], + request: user_event_service.ListUserEventsRequest, + response: user_event_service.ListUserEventsResponse, + *, + 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.recommendationengine_v1beta1.types.ListUserEventsRequest): + The initial request object. + response (google.cloud.recommendationengine_v1beta1.types.ListUserEventsResponse): + 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 = user_event_service.ListUserEventsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[user_event_service.ListUserEventsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[user_event.UserEvent]: + for page in self.pages: + yield from page.user_events + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUserEventsAsyncPager: + """A pager for iterating through ``list_user_events`` requests. + + This class thinly wraps an initial + :class:`google.cloud.recommendationengine_v1beta1.types.ListUserEventsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``user_events`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListUserEvents`` requests and continue to iterate + through the ``user_events`` field on the + corresponding responses. + + All the usual :class:`google.cloud.recommendationengine_v1beta1.types.ListUserEventsResponse` + 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[user_event_service.ListUserEventsResponse]], + request: user_event_service.ListUserEventsRequest, + response: user_event_service.ListUserEventsResponse, + *, + 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.recommendationengine_v1beta1.types.ListUserEventsRequest): + The initial request object. + response (google.cloud.recommendationengine_v1beta1.types.ListUserEventsResponse): + 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 = user_event_service.ListUserEventsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[user_event_service.ListUserEventsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[user_event.UserEvent]: + async def async_generator(): + async for page in self.pages: + for response in page.user_events: + 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/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/__init__.py new file mode 100644 index 00000000..7cff2187 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import UserEventServiceTransport +from .grpc import UserEventServiceGrpcTransport +from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] +_transport_registry['grpc'] = UserEventServiceGrpcTransport +_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport + +__all__ = ( + 'UserEventServiceTransport', + 'UserEventServiceGrpcTransport', + 'UserEventServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/base.py new file mode 100644 index 00000000..2def0397 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/base.py @@ -0,0 +1,269 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.recommendationengine_v1beta1.types import import_ +from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event +from google.cloud.recommendationengine_v1beta1.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-recommendations-ai', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class UserEventServiceTransport(abc.ABC): + """Abstract transport class for UserEventService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'recommendationengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials is service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.write_user_event: gapic_v1.method.wrap_method( + self.write_user_event, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.collect_user_event: gapic_v1.method.wrap_method( + self.collect_user_event, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_user_events: gapic_v1.method.wrap_method( + self.list_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.purge_user_events: gapic_v1.method.wrap_method( + self.purge_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.import_user_events: gapic_v1.method.wrap_method( + self.import_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Union[ + gcr_user_event.UserEvent, + Awaitable[gcr_user_event.UserEvent] + ]]: + raise NotImplementedError() + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + Union[ + httpbody_pb2.HttpBody, + Awaitable[httpbody_pb2.HttpBody] + ]]: + raise NotImplementedError() + + @property + def list_user_events(self) -> Callable[ + [user_event_service.ListUserEventsRequest], + Union[ + user_event_service.ListUserEventsResponse, + Awaitable[user_event_service.ListUserEventsResponse] + ]]: + raise NotImplementedError() + + @property + def purge_user_events(self) -> Callable[ + [user_event_service.PurgeUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def import_user_events(self) -> Callable[ + [import_.ImportUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'UserEventServiceTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc.py new file mode 100644 index 00000000..28b58907 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc.py @@ -0,0 +1,395 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.recommendationengine_v1beta1.types import import_ +from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event +from google.cloud.recommendationengine_v1beta1.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO + + +class UserEventServiceGrpcTransport(UserEventServiceTransport): + """gRPC backend transport for UserEventService. + + Service for ingesting end user actions on the customer + website. + + 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 = 'recommendationengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'recommendationengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + gcr_user_event.UserEvent]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + ~.UserEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'write_user_event' not in self._stubs: + self._stubs['write_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=gcr_user_event.UserEvent.deserialize, + ) + return self._stubs['write_user_event'] + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + httpbody_pb2.HttpBody]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Recommendations AI + JavaScript pixel. Users should not call this method + directly. + + Returns: + Callable[[~.CollectUserEventRequest], + ~.HttpBody]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect_user_event' not in self._stubs: + self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def list_user_events(self) -> Callable[ + [user_event_service.ListUserEventsRequest], + user_event_service.ListUserEventsResponse]: + r"""Return a callable for the list user events method over gRPC. + + Gets a list of user events within a time range, with + potential filtering. + + Returns: + Callable[[~.ListUserEventsRequest], + ~.ListUserEventsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_events' not in self._stubs: + self._stubs['list_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.UserEventService/ListUserEvents', + request_serializer=user_event_service.ListUserEventsRequest.serialize, + response_deserializer=user_event_service.ListUserEventsResponse.deserialize, + ) + return self._stubs['list_user_events'] + + @property + def purge_user_events(self) -> Callable[ + [user_event_service.PurgeUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the purge user events method over gRPC. + + Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + Returns: + Callable[[~.PurgeUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_user_events' not in self._stubs: + self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.UserEventService/PurgeUserEvents', + request_serializer=user_event_service.PurgeUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_user_events'] + + @property + def import_user_events(self) -> Callable[ + [import_.ImportUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_events' not in self._stubs: + self._stubs['import_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.UserEventService/ImportUserEvents', + request_serializer=import_.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + +__all__ = ( + 'UserEventServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..57e4e84b --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc_asyncio.py @@ -0,0 +1,399 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.recommendationengine_v1beta1.types import import_ +from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event +from google.cloud.recommendationengine_v1beta1.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import UserEventServiceGrpcTransport + + +class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): + """gRPC AsyncIO backend transport for UserEventService. + + Service for ingesting end user actions on the customer + website. + + 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 = 'recommendationengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'recommendationengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Awaitable[gcr_user_event.UserEvent]]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + Awaitable[~.UserEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'write_user_event' not in self._stubs: + self._stubs['write_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=gcr_user_event.UserEvent.deserialize, + ) + return self._stubs['write_user_event'] + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + Awaitable[httpbody_pb2.HttpBody]]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Recommendations AI + JavaScript pixel. Users should not call this method + directly. + + Returns: + Callable[[~.CollectUserEventRequest], + Awaitable[~.HttpBody]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect_user_event' not in self._stubs: + self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def list_user_events(self) -> Callable[ + [user_event_service.ListUserEventsRequest], + Awaitable[user_event_service.ListUserEventsResponse]]: + r"""Return a callable for the list user events method over gRPC. + + Gets a list of user events within a time range, with + potential filtering. + + Returns: + Callable[[~.ListUserEventsRequest], + Awaitable[~.ListUserEventsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_events' not in self._stubs: + self._stubs['list_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.UserEventService/ListUserEvents', + request_serializer=user_event_service.ListUserEventsRequest.serialize, + response_deserializer=user_event_service.ListUserEventsResponse.deserialize, + ) + return self._stubs['list_user_events'] + + @property + def purge_user_events(self) -> Callable[ + [user_event_service.PurgeUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the purge user events method over gRPC. + + Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + Returns: + Callable[[~.PurgeUserEventsRequest], + 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 'purge_user_events' not in self._stubs: + self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.UserEventService/PurgeUserEvents', + request_serializer=user_event_service.PurgeUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_user_events'] + + @property + def import_user_events(self) -> Callable[ + [import_.ImportUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + 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_user_events' not in self._stubs: + self._stubs['import_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.UserEventService/ImportUserEvents', + request_serializer=import_.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + +__all__ = ( + 'UserEventServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/__init__.py new file mode 100644 index 00000000..c23f7c8a --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/__init__.py @@ -0,0 +1,116 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .catalog import ( + CatalogItem, + Image, + ProductCatalogItem, +) +from .catalog_service import ( + CreateCatalogItemRequest, + DeleteCatalogItemRequest, + GetCatalogItemRequest, + ListCatalogItemsRequest, + ListCatalogItemsResponse, + UpdateCatalogItemRequest, +) +from .common import ( + FeatureMap, +) +from .import_ import ( + CatalogInlineSource, + GcsSource, + ImportCatalogItemsRequest, + ImportCatalogItemsResponse, + ImportErrorsConfig, + ImportMetadata, + ImportUserEventsRequest, + ImportUserEventsResponse, + InputConfig, + UserEventImportSummary, + UserEventInlineSource, +) +from .prediction_apikey_registry_service import ( + CreatePredictionApiKeyRegistrationRequest, + DeletePredictionApiKeyRegistrationRequest, + ListPredictionApiKeyRegistrationsRequest, + ListPredictionApiKeyRegistrationsResponse, + PredictionApiKeyRegistration, +) +from .prediction_service import ( + PredictRequest, + PredictResponse, +) +from .user_event import ( + EventDetail, + ProductDetail, + ProductEventDetail, + PurchaseTransaction, + UserEvent, + UserInfo, +) +from .user_event_service import ( + CollectUserEventRequest, + ListUserEventsRequest, + ListUserEventsResponse, + PurgeUserEventsMetadata, + PurgeUserEventsRequest, + PurgeUserEventsResponse, + WriteUserEventRequest, +) + +__all__ = ( + 'CatalogItem', + 'Image', + 'ProductCatalogItem', + 'CreateCatalogItemRequest', + 'DeleteCatalogItemRequest', + 'GetCatalogItemRequest', + 'ListCatalogItemsRequest', + 'ListCatalogItemsResponse', + 'UpdateCatalogItemRequest', + 'FeatureMap', + 'CatalogInlineSource', + 'GcsSource', + 'ImportCatalogItemsRequest', + 'ImportCatalogItemsResponse', + 'ImportErrorsConfig', + 'ImportMetadata', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'InputConfig', + 'UserEventImportSummary', + 'UserEventInlineSource', + 'CreatePredictionApiKeyRegistrationRequest', + 'DeletePredictionApiKeyRegistrationRequest', + 'ListPredictionApiKeyRegistrationsRequest', + 'ListPredictionApiKeyRegistrationsResponse', + 'PredictionApiKeyRegistration', + 'PredictRequest', + 'PredictResponse', + 'EventDetail', + 'ProductDetail', + 'ProductEventDetail', + 'PurchaseTransaction', + 'UserEvent', + 'UserInfo', + 'CollectUserEventRequest', + 'ListUserEventsRequest', + 'ListUserEventsResponse', + 'PurgeUserEventsMetadata', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/catalog.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/catalog.py new file mode 100644 index 00000000..11b0fcb9 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/catalog.py @@ -0,0 +1,312 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.recommendationengine_v1beta1.types import common + + +__protobuf__ = proto.module( + package='google.cloud.recommendationengine.v1beta1', + manifest={ + 'CatalogItem', + 'ProductCatalogItem', + 'Image', + }, +) + + +class CatalogItem(proto.Message): + r"""CatalogItem captures all metadata information of items to be + recommended. + + Attributes: + id (str): + Required. Catalog item identifier. UTF-8 + encoded string with a length limit of 128 bytes. + This id must be unique among all catalog items + within the same catalog. It should also be used + when logging user events in order for the user + events to be joined with the Catalog. + category_hierarchies (Sequence[google.cloud.recommendationengine_v1beta1.types.CatalogItem.CategoryHierarchy]): + Required. Catalog item categories. This field is repeated + for supporting one catalog item belonging to several + parallel category hierarchies. + + For example, if a shoes product belongs to both ["Shoes & + Accessories" -> "Shoes"] and ["Sports & Fitness" -> + "Athletic Clothing" -> "Shoes"], it could be represented as: + + :: + + "categoryHierarchies": [ + { "categories": ["Shoes & Accessories", "Shoes"]}, + { "categories": ["Sports & Fitness", "Athletic Clothing", "Shoes"] } + ] + title (str): + Required. Catalog item title. UTF-8 encoded + string with a length limit of 1 KiB. + description (str): + Optional. Catalog item description. UTF-8 + encoded string with a length limit of 5 KiB. + item_attributes (google.cloud.recommendationengine_v1beta1.types.FeatureMap): + Optional. Highly encouraged. Extra catalog + item attributes to be included in the + recommendation model. For example, for retail + products, this could include the store name, + vendor, style, color, etc. These are very strong + signals for recommendation model, thus we highly + recommend providing the item attributes here. + language_code (str): + Optional. Language of the title/description/item_attributes. + Use language tags defined by BCP 47. + https://www.rfc-editor.org/rfc/bcp/bcp47.txt. Our supported + language codes include 'en', 'es', 'fr', 'de', 'ar', 'fa', + 'zh', 'ja', 'ko', 'sv', 'ro', 'nl'. For other languages, + contact your Google account manager. + tags (Sequence[str]): + Optional. Filtering tags associated with the + catalog item. Each tag should be a UTF-8 encoded + string with a length limit of 1 KiB. + This tag can be used for filtering + recommendation results by passing the tag as + part of the predict request filter. + item_group_id (str): + Optional. Variant group identifier for prediction results. + UTF-8 encoded string with a length limit of 128 bytes. + + This field must be enabled before it can be used. `Learn + more `__. + product_metadata (google.cloud.recommendationengine_v1beta1.types.ProductCatalogItem): + Optional. Metadata specific to retail + products. + """ + + class CategoryHierarchy(proto.Message): + r"""Category represents catalog item category hierarchy. + Attributes: + categories (Sequence[str]): + Required. Catalog item categories. Each + category should be a UTF-8 encoded string with a + length limit of 2 KiB. + Note that the order in the list denotes the + specificity (from least to most specific). + """ + + categories = proto.RepeatedField( + proto.STRING, + number=1, + ) + + id = proto.Field( + proto.STRING, + number=1, + ) + category_hierarchies = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=CategoryHierarchy, + ) + title = proto.Field( + proto.STRING, + number=3, + ) + description = proto.Field( + proto.STRING, + number=4, + ) + item_attributes = proto.Field( + proto.MESSAGE, + number=5, + message=common.FeatureMap, + ) + language_code = proto.Field( + proto.STRING, + number=6, + ) + tags = proto.RepeatedField( + proto.STRING, + number=8, + ) + item_group_id = proto.Field( + proto.STRING, + number=9, + ) + product_metadata = proto.Field( + proto.MESSAGE, + number=10, + oneof='recommendation_type', + message='ProductCatalogItem', + ) + + +class ProductCatalogItem(proto.Message): + r"""ProductCatalogItem captures item metadata specific to retail + products. + + Attributes: + exact_price (google.cloud.recommendationengine_v1beta1.types.ProductCatalogItem.ExactPrice): + Optional. The exact product price. + price_range (google.cloud.recommendationengine_v1beta1.types.ProductCatalogItem.PriceRange): + Optional. The product price range. + costs (Sequence[google.cloud.recommendationengine_v1beta1.types.ProductCatalogItem.CostsEntry]): + Optional. A map to pass the costs associated with the + product. + + For example: {"manufacturing": 45.5} The profit of selling + this item is computed like so: + + - If 'exactPrice' is provided, profit = displayPrice - + sum(costs) + - If 'priceRange' is provided, profit = minPrice - + sum(costs) + currency_code (str): + Optional. Only required if the price is set. + Currency code for price/costs. Use three- + character ISO-4217 code. + stock_state (google.cloud.recommendationengine_v1beta1.types.ProductCatalogItem.StockState): + Optional. Online stock state of the catalog item. Default is + ``IN_STOCK``. + available_quantity (int): + Optional. The available quantity of the item. + canonical_product_uri (str): + Optional. Canonical URL directly linking to + the item detail page with a length limit of 5 + KiB.. + images (Sequence[google.cloud.recommendationengine_v1beta1.types.Image]): + Optional. Product images for the catalog + item. + """ + class StockState(proto.Enum): + r"""Item stock state. If this field is unspecified, the item is + assumed to be in stock. + """ + _pb_options = {'allow_alias': True} + STOCK_STATE_UNSPECIFIED = 0 + IN_STOCK = 0 + OUT_OF_STOCK = 1 + PREORDER = 2 + BACKORDER = 3 + + class ExactPrice(proto.Message): + r"""Exact product price. + Attributes: + display_price (float): + Optional. Display price of the product. + original_price (float): + Optional. Price of the product without any + discount. If zero, by default set to be the + 'displayPrice'. + """ + + display_price = proto.Field( + proto.FLOAT, + number=1, + ) + original_price = proto.Field( + proto.FLOAT, + number=2, + ) + + class PriceRange(proto.Message): + r"""Product price range when there are a range of prices for + different variations of the same product. + + Attributes: + min_ (float): + Required. The minimum product price. + max_ (float): + Required. The maximum product price. + """ + + min_ = proto.Field( + proto.FLOAT, + number=1, + ) + max_ = proto.Field( + proto.FLOAT, + number=2, + ) + + exact_price = proto.Field( + proto.MESSAGE, + number=1, + oneof='price', + message=ExactPrice, + ) + price_range = proto.Field( + proto.MESSAGE, + number=2, + oneof='price', + message=PriceRange, + ) + costs = proto.MapField( + proto.STRING, + proto.FLOAT, + number=3, + ) + currency_code = proto.Field( + proto.STRING, + number=4, + ) + stock_state = proto.Field( + proto.ENUM, + number=5, + enum=StockState, + ) + available_quantity = proto.Field( + proto.INT64, + number=6, + ) + canonical_product_uri = proto.Field( + proto.STRING, + number=7, + ) + images = proto.RepeatedField( + proto.MESSAGE, + number=8, + message='Image', + ) + + +class Image(proto.Message): + r"""Catalog item thumbnail/detail image. + Attributes: + uri (str): + Required. URL of the image with a length + limit of 5 KiB. + height (int): + Optional. Height of the image in number of + pixels. + width (int): + Optional. Width of the image in number of + pixels. + """ + + uri = proto.Field( + proto.STRING, + number=1, + ) + height = proto.Field( + proto.INT32, + number=2, + ) + width = proto.Field( + proto.INT32, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/catalog_service.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/catalog_service.py new file mode 100644 index 00000000..2ebd593e --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/catalog_service.py @@ -0,0 +1,177 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.recommendationengine_v1beta1.types import catalog +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.recommendationengine.v1beta1', + manifest={ + 'CreateCatalogItemRequest', + 'GetCatalogItemRequest', + 'ListCatalogItemsRequest', + 'ListCatalogItemsResponse', + 'UpdateCatalogItemRequest', + 'DeleteCatalogItemRequest', + }, +) + + +class CreateCatalogItemRequest(proto.Message): + r"""Request message for CreateCatalogItem method. + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + catalog_item (google.cloud.recommendationengine_v1beta1.types.CatalogItem): + Required. The catalog item to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + catalog_item = proto.Field( + proto.MESSAGE, + number=2, + message=catalog.CatalogItem, + ) + + +class GetCatalogItemRequest(proto.Message): + r"""Request message for GetCatalogItem method. + Attributes: + name (str): + Required. Full resource name of catalog item, such as + ``projects/*/locations/global/catalogs/default_catalog/catalogitems/some_catalog_item_id``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListCatalogItemsRequest(proto.Message): + r"""Request message for ListCatalogItems method. + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + page_size (int): + Optional. Maximum number of results to return + per page. If zero, the service will choose a + reasonable default. + page_token (str): + Optional. The previous + ListCatalogItemsResponse.next_page_token. + filter (str): + Optional. A filter to apply on the list + results. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + + +class ListCatalogItemsResponse(proto.Message): + r"""Response message for ListCatalogItems method. + Attributes: + catalog_items (Sequence[google.cloud.recommendationengine_v1beta1.types.CatalogItem]): + The catalog items. + next_page_token (str): + If empty, the list is complete. If nonempty, the token to + pass to the next request's + ListCatalogItemRequest.page_token. + """ + + @property + def raw_page(self): + return self + + catalog_items = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=catalog.CatalogItem, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateCatalogItemRequest(proto.Message): + r"""Request message for UpdateCatalogItem method. + Attributes: + name (str): + Required. Full resource name of catalog item, such as + "projects/*/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_id". + catalog_item (google.cloud.recommendationengine_v1beta1.types.CatalogItem): + Required. The catalog item to update/create. The + 'catalog_item_id' field has to match that in the 'name'. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Indicates which fields in the + provided 'item' to update. If not set, will by + default update all fields. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + catalog_item = proto.Field( + proto.MESSAGE, + number=2, + message=catalog.CatalogItem, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteCatalogItemRequest(proto.Message): + r"""Request message for DeleteCatalogItem method. + Attributes: + name (str): + Required. Full resource name of catalog item, such as + ``projects/*/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_id``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/common.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/common.py new file mode 100644 index 00000000..f337c80a --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/common.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.recommendationengine.v1beta1', + manifest={ + 'FeatureMap', + }, +) + + +class FeatureMap(proto.Message): + r"""FeatureMap represents extra features that customers want to + include in the recommendation model for catalogs/user events as + categorical/numerical features. + + Attributes: + categorical_features (Sequence[google.cloud.recommendationengine_v1beta1.types.FeatureMap.CategoricalFeaturesEntry]): + Categorical features that can take on one of a limited + number of possible values. Some examples would be the + brand/maker of a product, or country of a customer. + + Feature names and values must be UTF-8 encoded strings. + + For example: + ``{ "colors": {"value": ["yellow", "green"]}, "sizes": {"value":["S", "M"]}`` + numerical_features (Sequence[google.cloud.recommendationengine_v1beta1.types.FeatureMap.NumericalFeaturesEntry]): + Numerical features. Some examples would be the height/weight + of a product, or age of a customer. + + Feature names must be UTF-8 encoded strings. + + For example: + ``{ "lengths_cm": {"value":[2.3, 15.4]}, "heights_cm": {"value":[8.1, 6.4]} }`` + """ + + class StringList(proto.Message): + r"""A list of string features. + Attributes: + value (Sequence[str]): + String feature value with a length limit of + 128 bytes. + """ + + value = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class FloatList(proto.Message): + r"""A list of float features. + Attributes: + value (Sequence[float]): + Float feature value. + """ + + value = proto.RepeatedField( + proto.FLOAT, + number=1, + ) + + categorical_features = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message=StringList, + ) + numerical_features = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=FloatList, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/import_.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/import_.py new file mode 100644 index 00000000..292e8400 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/import_.py @@ -0,0 +1,373 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.recommendationengine_v1beta1.types import catalog +from google.cloud.recommendationengine_v1beta1.types import user_event +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.recommendationengine.v1beta1', + manifest={ + 'GcsSource', + 'CatalogInlineSource', + 'UserEventInlineSource', + 'ImportErrorsConfig', + 'ImportCatalogItemsRequest', + 'ImportUserEventsRequest', + 'InputConfig', + 'ImportMetadata', + 'ImportCatalogItemsResponse', + 'ImportUserEventsResponse', + 'UserEventImportSummary', + }, +) + + +class GcsSource(proto.Message): + r"""Google Cloud Storage location for input content. + format. + + Attributes: + input_uris (Sequence[str]): + Required. Google Cloud Storage URIs to input files. URI can + be up to 2000 characters long. URIs can match the full + object path (for example, + ``gs://bucket/directory/object.json``) or a pattern matching + one or more files, such as ``gs://bucket/directory/*.json``. + A request can contain at most 100 files, and each file can + be up to 2 GB. See `Importing catalog + information `__ for + the expected file format and setup instructions. + """ + + input_uris = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class CatalogInlineSource(proto.Message): + r"""The inline source for the input config for ImportCatalogItems + method. + + Attributes: + catalog_items (Sequence[google.cloud.recommendationengine_v1beta1.types.CatalogItem]): + Optional. A list of catalog items to + update/create. Recommended max of 10k items. + """ + + catalog_items = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=catalog.CatalogItem, + ) + + +class UserEventInlineSource(proto.Message): + r"""The inline source for the input config for ImportUserEvents + method. + + Attributes: + user_events (Sequence[google.cloud.recommendationengine_v1beta1.types.UserEvent]): + Optional. A list of user events to import. + Recommended max of 10k items. + """ + + user_events = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=user_event.UserEvent, + ) + + +class ImportErrorsConfig(proto.Message): + r"""Configuration of destination for Import related errors. + Attributes: + gcs_prefix (str): + Google Cloud Storage path for import errors. This must be an + empty, existing Cloud Storage bucket. Import errors will be + written to a file in this bucket, one per line, as a + JSON-encoded ``google.rpc.Status`` message. + """ + + gcs_prefix = proto.Field( + proto.STRING, + number=1, + oneof='destination', + ) + + +class ImportCatalogItemsRequest(proto.Message): + r"""Request message for Import methods. + Attributes: + parent (str): + Required. + ``projects/1234/locations/global/catalogs/default_catalog`` + request_id (str): + Optional. Unique identifier provided by + client, within the ancestor dataset scope. + Ensures idempotency and used for request + deduplication. Server-generated if unspecified. + Up to 128 characters long. This is returned as + google.longrunning.Operation.name in the + response. + input_config (google.cloud.recommendationengine_v1beta1.types.InputConfig): + Required. The desired input location of the + data. + errors_config (google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig): + Optional. The desired location of errors + incurred during the Import. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + request_id = proto.Field( + proto.STRING, + number=2, + ) + input_config = proto.Field( + proto.MESSAGE, + number=3, + message='InputConfig', + ) + errors_config = proto.Field( + proto.MESSAGE, + number=4, + message='ImportErrorsConfig', + ) + + +class ImportUserEventsRequest(proto.Message): + r"""Request message for the ImportUserEvents request. + Attributes: + parent (str): + Required. + ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store`` + request_id (str): + Optional. Unique identifier provided by client, within the + ancestor dataset scope. Ensures idempotency for expensive + long running operations. Server-generated if unspecified. Up + to 128 characters long. This is returned as + google.longrunning.Operation.name in the response. Note that + this field must not be set if the desired input config is + catalog_inline_source. + input_config (google.cloud.recommendationengine_v1beta1.types.InputConfig): + Required. The desired input location of the + data. + errors_config (google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig): + Optional. The desired location of errors + incurred during the Import. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + request_id = proto.Field( + proto.STRING, + number=2, + ) + input_config = proto.Field( + proto.MESSAGE, + number=3, + message='InputConfig', + ) + errors_config = proto.Field( + proto.MESSAGE, + number=4, + message='ImportErrorsConfig', + ) + + +class InputConfig(proto.Message): + r"""The input config source. + Attributes: + catalog_inline_source (google.cloud.recommendationengine_v1beta1.types.CatalogInlineSource): + The Inline source for the input content for + Catalog items. + gcs_source (google.cloud.recommendationengine_v1beta1.types.GcsSource): + Google Cloud Storage location for the input + content. + user_event_inline_source (google.cloud.recommendationengine_v1beta1.types.UserEventInlineSource): + The Inline source for the input content for + UserEvents. + """ + + catalog_inline_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='CatalogInlineSource', + ) + gcs_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='GcsSource', + ) + user_event_inline_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='UserEventInlineSource', + ) + + +class ImportMetadata(proto.Message): + r"""Metadata related to the progress of the Import operation. + This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + operation_name (str): + Name of the operation. + request_id (str): + Id of the request / operation. This is + parroting back the requestId that was passed in + the request. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + success_count (int): + Count of entries that were processed + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + operation_name = proto.Field( + proto.STRING, + number=5, + ) + request_id = proto.Field( + proto.STRING, + number=3, + ) + create_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + success_count = proto.Field( + proto.INT64, + number=1, + ) + failure_count = proto.Field( + proto.INT64, + number=2, + ) + update_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + +class ImportCatalogItemsResponse(proto.Message): + r"""Response of the ImportCatalogItemsRequest. If the long + running operation is done, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig): + Echoes the destination for the complete + errors in the request if set. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorsConfig', + ) + + +class ImportUserEventsResponse(proto.Message): + r"""Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (Sequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig): + Echoes the destination for the complete + errors if this field was set in the request. + import_summary (google.cloud.recommendationengine_v1beta1.types.UserEventImportSummary): + Aggregated statistics of user event import + status. + """ + + error_samples = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorsConfig', + ) + import_summary = proto.Field( + proto.MESSAGE, + number=3, + message='UserEventImportSummary', + ) + + +class UserEventImportSummary(proto.Message): + r"""A summary of import result. The UserEventImportSummary + summarizes the import status for user events. + + Attributes: + joined_events_count (int): + Count of user events imported with complete + existing catalog information. + unjoined_events_count (int): + Count of user events imported, but with + catalog information not found in the imported + catalog. + """ + + joined_events_count = proto.Field( + proto.INT64, + number=1, + ) + unjoined_events_count = proto.Field( + proto.INT64, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/prediction_apikey_registry_service.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/prediction_apikey_registry_service.py new file mode 100644 index 00000000..b0eba7f9 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/prediction_apikey_registry_service.py @@ -0,0 +1,138 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.recommendationengine.v1beta1', + manifest={ + 'PredictionApiKeyRegistration', + 'CreatePredictionApiKeyRegistrationRequest', + 'ListPredictionApiKeyRegistrationsRequest', + 'ListPredictionApiKeyRegistrationsResponse', + 'DeletePredictionApiKeyRegistrationRequest', + }, +) + + +class PredictionApiKeyRegistration(proto.Message): + r"""Registered Api Key. + Attributes: + api_key (str): + The API key. + """ + + api_key = proto.Field( + proto.STRING, + number=1, + ) + + +class CreatePredictionApiKeyRegistrationRequest(proto.Message): + r"""Request message for the ``CreatePredictionApiKeyRegistration`` + method. + + Attributes: + parent (str): + Required. The parent resource path. + ``projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store``. + prediction_api_key_registration (google.cloud.recommendationengine_v1beta1.types.PredictionApiKeyRegistration): + Required. The prediction API key + registration. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + prediction_api_key_registration = proto.Field( + proto.MESSAGE, + number=2, + message='PredictionApiKeyRegistration', + ) + + +class ListPredictionApiKeyRegistrationsRequest(proto.Message): + r"""Request message for the ``ListPredictionApiKeyRegistrations``. + Attributes: + parent (str): + Required. The parent placement resource name such as + ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store`` + page_size (int): + Optional. Maximum number of results to return + per page. If unset, the service will choose a + reasonable default. + page_token (str): + Optional. The previous + ``ListPredictionApiKeyRegistration.nextPageToken``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListPredictionApiKeyRegistrationsResponse(proto.Message): + r"""Response message for the ``ListPredictionApiKeyRegistrations``. + Attributes: + prediction_api_key_registrations (Sequence[google.cloud.recommendationengine_v1beta1.types.PredictionApiKeyRegistration]): + The list of registered API keys. + next_page_token (str): + If empty, the list is complete. If nonempty, pass the token + to the next request's + ``ListPredictionApiKeysRegistrationsRequest.pageToken``. + """ + + @property + def raw_page(self): + return self + + prediction_api_key_registrations = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='PredictionApiKeyRegistration', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class DeletePredictionApiKeyRegistrationRequest(proto.Message): + r"""Request message for ``DeletePredictionApiKeyRegistration`` method. + Attributes: + name (str): + Required. The API key to unregister including full resource + path. + ``projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/prediction_service.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/prediction_service.py new file mode 100644 index 00000000..3c7988b4 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/prediction_service.py @@ -0,0 +1,271 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.recommendationengine.v1beta1', + manifest={ + 'PredictRequest', + 'PredictResponse', + }, +) + + +class PredictRequest(proto.Message): + r"""Request message for Predict method. + Attributes: + name (str): + Required. Full resource name of the format: + ``{name=projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/placements/*}`` + The id of the recommendation engine placement. This id is + used to identify the set of models that will be used to make + the prediction. + + We currently support three placements with the following IDs + by default: + + - ``shopping_cart``: Predicts items frequently bought + together with one or more catalog items in the same + shopping session. Commonly displayed after + ``add-to-cart`` events, on product detail pages, or on + the shopping cart page. + + - ``home_page``: Predicts the next product that a user will + most likely engage with or purchase based on the shopping + or viewing history of the specified ``userId`` or + ``visitorId``. For example - Recommendations for you. + + - ``product_detail``: Predicts the next product that a user + will most likely engage with or purchase. The prediction + is based on the shopping or viewing history of the + specified ``userId`` or ``visitorId`` and its relevance + to a specified ``CatalogItem``. Typically used on product + detail pages. For example - More items like this. + + - ``recently_viewed_default``: Returns up to 75 items + recently viewed by the specified ``userId`` or + ``visitorId``, most recent ones first. Returns nothing if + neither of them has viewed any items yet. For example - + Recently viewed. + + The full list of available placements can be seen at + https://console.cloud.google.com/recommendation/datafeeds/default_catalog/dashboard + user_event (google.cloud.recommendationengine_v1beta1.types.UserEvent): + Required. Context about the user, what they + are looking at and what action they took to + trigger the predict request. Note that this user + event detail won't be ingested to userEvent + logs. Thus, a separate userEvent write request + is required for event logging. + page_size (int): + Optional. Maximum number of results to return + per page. Set this property to the number of + prediction results required. If zero, the + service will choose a reasonable default. + page_token (str): + Optional. The previous PredictResponse.next_page_token. + filter (str): + Optional. Filter for restricting prediction results. Accepts + values for tags and the ``filterOutOfStockItems`` flag. + + - Tag expressions. Restricts predictions to items that + match all of the specified tags. Boolean operators ``OR`` + and ``NOT`` are supported if the expression is enclosed + in parentheses, and must be separated from the tag values + by a space. ``-"tagA"`` is also supported and is + equivalent to ``NOT "tagA"``. Tag values must be double + quoted UTF-8 encoded strings with a size limit of 1 KiB. + + - filterOutOfStockItems. Restricts predictions to items + that do not have a stockState value of OUT_OF_STOCK. + + Examples: + + - tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT + "promotional") + - filterOutOfStockItems tag=(-"promotional") + - filterOutOfStockItems + dry_run (bool): + Optional. Use dryRun mode for this prediction + query. If set to true, a dummy model will be + used that returns arbitrary catalog items. Note + that the dryRun mode should only be used for + testing the API, or if the model is not ready. + params (Sequence[google.cloud.recommendationengine_v1beta1.types.PredictRequest.ParamsEntry]): + Optional. Additional domain specific parameters for the + predictions. + + Allowed values: + + - ``returnCatalogItem``: Boolean. If set to true, the + associated catalogItem object will be returned in the + ``PredictResponse.PredictionResult.itemMetadata`` object + in the method response. + - ``returnItemScore``: Boolean. If set to true, the + prediction 'score' corresponding to each returned item + will be set in the ``metadata`` field in the prediction + response. The given 'score' indicates the probability of + an item being clicked/purchased given the user's context + and history. + labels (Sequence[google.cloud.recommendationengine_v1beta1.types.PredictRequest.LabelsEntry]): + Optional. The labels for the predict request. + + - Label keys can contain lowercase letters, digits and + hyphens, must start with a letter, and must end with a + letter or digit. + - Non-zero label values can contain lowercase letters, + digits and hyphens, must start with a letter, and must + end with a letter or digit. + - No more than 64 labels can be associated with a given + request. + + See https://goo.gl/xmQnxf for more information on and + examples of labels. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_user_event.UserEvent, + ) + page_size = proto.Field( + proto.INT32, + number=7, + ) + page_token = proto.Field( + proto.STRING, + number=8, + ) + filter = proto.Field( + proto.STRING, + number=3, + ) + dry_run = proto.Field( + proto.BOOL, + number=4, + ) + params = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=6, + message=struct_pb2.Value, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=9, + ) + + +class PredictResponse(proto.Message): + r"""Response message for predict method. + Attributes: + results (Sequence[google.cloud.recommendationengine_v1beta1.types.PredictResponse.PredictionResult]): + A list of recommended items. The order + represents the ranking (from the most relevant + item to the least). + recommendation_token (str): + A unique recommendation token. This should be + included in the user event logs resulting from + this recommendation, which enables accurate + attribution of recommendation model performance. + items_missing_in_catalog (Sequence[str]): + IDs of items in the request that were missing + from the catalog. + dry_run (bool): + True if the dryRun property was set in the + request. + metadata (Sequence[google.cloud.recommendationengine_v1beta1.types.PredictResponse.MetadataEntry]): + Additional domain specific prediction + response metadata. + next_page_token (str): + If empty, the list is complete. If nonempty, the token to + pass to the next request's PredictRequest.page_token. + """ + + class PredictionResult(proto.Message): + r"""PredictionResult represents the recommendation prediction + results. + + Attributes: + id (str): + ID of the recommended catalog item + item_metadata (Sequence[google.cloud.recommendationengine_v1beta1.types.PredictResponse.PredictionResult.ItemMetadataEntry]): + Additional item metadata / annotations. + + Possible values: + + - ``catalogItem``: JSON representation of the catalogItem. + Will be set if ``returnCatalogItem`` is set to true in + ``PredictRequest.params``. + - ``score``: Prediction score in double value. Will be set + if ``returnItemScore`` is set to true in + ``PredictRequest.params``. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + item_metadata = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=struct_pb2.Value, + ) + + @property + def raw_page(self): + return self + + results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=PredictionResult, + ) + recommendation_token = proto.Field( + proto.STRING, + number=2, + ) + items_missing_in_catalog = proto.RepeatedField( + proto.STRING, + number=3, + ) + dry_run = proto.Field( + proto.BOOL, + number=4, + ) + metadata = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=5, + message=struct_pb2.Value, + ) + next_page_token = proto.Field( + proto.STRING, + number=6, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/recommendationengine_resources.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/recommendationengine_resources.py new file mode 100644 index 00000000..d9dca252 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/recommendationengine_resources.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + + +__protobuf__ = proto.module( + package='google.cloud.recommendationengine.v1beta1', + manifest={ + }, +) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/user_event.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/user_event.py new file mode 100644 index 00000000..111cd038 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/user_event.py @@ -0,0 +1,513 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.recommendationengine_v1beta1.types import catalog +from google.cloud.recommendationengine_v1beta1.types import common +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.recommendationengine.v1beta1', + manifest={ + 'UserEvent', + 'UserInfo', + 'EventDetail', + 'ProductEventDetail', + 'PurchaseTransaction', + 'ProductDetail', + }, +) + + +class UserEvent(proto.Message): + r"""UserEvent captures all metadata information recommendation + engine needs to know about how end users interact with + customers' website. + + Attributes: + event_type (str): + Required. User event type. Allowed values are: + + - ``add-to-cart`` Products being added to cart. + - ``add-to-list`` Items being added to a list (shopping + list, favorites etc). + - ``category-page-view`` Special pages such as sale or + promotion pages viewed. + - ``checkout-start`` User starting a checkout process. + - ``detail-page-view`` Products detail page viewed. + - ``home-page-view`` Homepage viewed. + - ``page-visit`` Generic page visits not included in the + event types above. + - ``purchase-complete`` User finishing a purchase. + - ``refund`` Purchased items being refunded or returned. + - ``remove-from-cart`` Products being removed from cart. + - ``remove-from-list`` Items being removed from a list. + - ``search`` Product search. + - ``shopping-cart-page-view`` User viewing a shopping cart. + - ``impression`` List of items displayed. Used by Google + Tag Manager. + user_info (google.cloud.recommendationengine_v1beta1.types.UserInfo): + Required. User information. + event_detail (google.cloud.recommendationengine_v1beta1.types.EventDetail): + Optional. User event detailed information + common across different recommendation types. + product_event_detail (google.cloud.recommendationengine_v1beta1.types.ProductEventDetail): + Optional. Retail product specific user event metadata. + + This field is required for the following event types: + + - ``add-to-cart`` + - ``add-to-list`` + - ``category-page-view`` + - ``checkout-start`` + - ``detail-page-view`` + - ``purchase-complete`` + - ``refund`` + - ``remove-from-cart`` + - ``remove-from-list`` + - ``search`` + + This field is optional for the following event types: + + - ``page-visit`` + - ``shopping-cart-page-view`` - note that + 'product_event_detail' should be set for this unless the + shopping cart is empty. + + This field is not allowed for the following event types: + + - ``home-page-view`` + event_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. Only required for ImportUserEvents + method. Timestamp of user event created. + event_source (google.cloud.recommendationengine_v1beta1.types.UserEvent.EventSource): + Optional. This field should *not* be set when using + JavaScript pixel or the Recommendations AI Tag. Defaults to + ``EVENT_SOURCE_UNSPECIFIED``. + """ + class EventSource(proto.Enum): + r"""User event source.""" + EVENT_SOURCE_UNSPECIFIED = 0 + AUTOML = 1 + ECOMMERCE = 2 + BATCH_UPLOAD = 3 + + event_type = proto.Field( + proto.STRING, + number=1, + ) + user_info = proto.Field( + proto.MESSAGE, + number=2, + message='UserInfo', + ) + event_detail = proto.Field( + proto.MESSAGE, + number=3, + message='EventDetail', + ) + product_event_detail = proto.Field( + proto.MESSAGE, + number=4, + message='ProductEventDetail', + ) + event_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + event_source = proto.Field( + proto.ENUM, + number=6, + enum=EventSource, + ) + + +class UserInfo(proto.Message): + r"""Information of end users. + Attributes: + visitor_id (str): + Required. A unique identifier for tracking + visitors with a length limit of 128 bytes. + + For example, this could be implemented with a + http cookie, which should be able to uniquely + identify a visitor on a single device. This + unique identifier should not change if the + visitor log in/out of the website. Maximum + length 128 bytes. Cannot be empty. + user_id (str): + Optional. Unique identifier for logged-in + user with a length limit of 128 bytes. Required + only for logged-in users. + ip_address (str): + Optional. IP address of the user. This could be either IPv4 + (e.g. 104.133.9.80) or IPv6 (e.g. + 2001:0db8:85a3:0000:0000:8a2e:0370:7334). This should *not* + be set when using the javascript pixel or if + ``direct_user_request`` is set. Used to extract location + information for personalization. + user_agent (str): + Optional. User agent as included in the HTTP header. UTF-8 + encoded string with a length limit of 1 KiB. + + This should *not* be set when using the JavaScript pixel or + if ``directUserRequest`` is set. + direct_user_request (bool): + Optional. Indicates if the request is made directly from the + end user in which case the user_agent and ip_address fields + can be populated from the HTTP request. This should *not* be + set when using the javascript pixel. This flag should be set + only if the API request is made directly from the end user + such as a mobile app (and not if a gateway or a server is + processing and pushing the user events). + """ + + visitor_id = proto.Field( + proto.STRING, + number=1, + ) + user_id = proto.Field( + proto.STRING, + number=2, + ) + ip_address = proto.Field( + proto.STRING, + number=3, + ) + user_agent = proto.Field( + proto.STRING, + number=4, + ) + direct_user_request = proto.Field( + proto.BOOL, + number=5, + ) + + +class EventDetail(proto.Message): + r"""User event details shared by all recommendation types. + Attributes: + uri (str): + Optional. Complete url (window.location.href) + of the user's current page. When using the + JavaScript pixel, this value is filled in + automatically. Maximum length 5KB. + referrer_uri (str): + Optional. The referrer url of the current + page. When using the JavaScript pixel, this + value is filled in automatically. + page_view_id (str): + Optional. A unique id of a web page view. This should be + kept the same for all user events triggered from the same + pageview. For example, an item detail page view could + trigger multiple events as the user is browsing the page. + The ``pageViewId`` property should be kept the same for all + these events so that they can be grouped together properly. + This ``pageViewId`` will be automatically generated if using + the JavaScript pixel. + experiment_ids (Sequence[str]): + Optional. A list of identifiers for the + independent experiment groups this user event + belongs to. This is used to distinguish between + user events associated with different experiment + setups (e.g. using Recommendation Engine system, + using different recommendation models). + recommendation_token (str): + Optional. Recommendation token included in the + recommendation prediction response. + + This field enables accurate attribution of recommendation + model performance. + + This token enables us to accurately attribute page view or + purchase back to the event and the particular predict + response containing this clicked/purchased item. If user + clicks on product K in the recommendation results, pass the + ``PredictResponse.recommendationToken`` property as a url + parameter to product K's page. When recording events on + product K's page, log the + PredictResponse.recommendation_token to this field. + + Optional, but highly encouraged for user events that are the + result of a recommendation prediction query. + event_attributes (google.cloud.recommendationengine_v1beta1.types.FeatureMap): + Optional. Extra user event features to include in the + recommendation model. + + For product recommendation, an example of extra user + information is traffic_channel, i.e. how user arrives at the + site. Users can arrive at the site by coming to the site + directly, or coming through Google search, and etc. + """ + + uri = proto.Field( + proto.STRING, + number=1, + ) + referrer_uri = proto.Field( + proto.STRING, + number=6, + ) + page_view_id = proto.Field( + proto.STRING, + number=2, + ) + experiment_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + recommendation_token = proto.Field( + proto.STRING, + number=4, + ) + event_attributes = proto.Field( + proto.MESSAGE, + number=5, + message=common.FeatureMap, + ) + + +class ProductEventDetail(proto.Message): + r"""ProductEventDetail captures user event information specific + to retail products. + + Attributes: + search_query (str): + Required for ``search`` events. Other event types should not + set this field. The user's search query as UTF-8 encoded + text with a length limit of 5 KiB. + page_categories (Sequence[google.cloud.recommendationengine_v1beta1.types.CatalogItem.CategoryHierarchy]): + Required for ``category-page-view`` events. Other event + types should not set this field. The categories associated + with a category page. Category pages include special pages + such as sales or promotions. For instance, a special sale + page may have the category hierarchy: categories : ["Sales", + "2017 Black Friday Deals"]. + product_details (Sequence[google.cloud.recommendationengine_v1beta1.types.ProductDetail]): + The main product details related to the event. + + This field is required for the following event types: + + - ``add-to-cart`` + - ``add-to-list`` + - ``checkout-start`` + - ``detail-page-view`` + - ``purchase-complete`` + - ``refund`` + - ``remove-from-cart`` + - ``remove-from-list`` + + This field is optional for the following event types: + + - ``page-visit`` + - ``shopping-cart-page-view`` - note that 'product_details' + should be set for this unless the shopping cart is empty. + + This field is not allowed for the following event types: + + - ``category-page-view`` + - ``home-page-view`` + - ``search`` + list_id (str): + Required for ``add-to-list`` and ``remove-from-list`` + events. The id or name of the list that the item is being + added to or removed from. Other event types should not set + this field. + cart_id (str): + Optional. The id or name of the associated shopping cart. + This id is used to associate multiple items added or present + in the cart before purchase. + + This can only be set for ``add-to-cart``, + ``remove-from-cart``, ``checkout-start``, + ``purchase-complete``, or ``shopping-cart-page-view`` + events. + purchase_transaction (google.cloud.recommendationengine_v1beta1.types.PurchaseTransaction): + Optional. A transaction represents the entire purchase + transaction. Required for ``purchase-complete`` events. + Optional for ``checkout-start`` events. Other event types + should not set this field. + """ + + search_query = proto.Field( + proto.STRING, + number=1, + ) + page_categories = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=catalog.CatalogItem.CategoryHierarchy, + ) + product_details = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='ProductDetail', + ) + list_id = proto.Field( + proto.STRING, + number=4, + ) + cart_id = proto.Field( + proto.STRING, + number=5, + ) + purchase_transaction = proto.Field( + proto.MESSAGE, + number=6, + message='PurchaseTransaction', + ) + + +class PurchaseTransaction(proto.Message): + r"""A transaction represents the entire purchase transaction. + Attributes: + id (str): + Optional. The transaction ID with a length + limit of 128 bytes. + revenue (float): + Required. Total revenue or grand total associated with the + transaction. This value include shipping, tax, or other + adjustments to total revenue that you want to include as + part of your revenue calculations. This field is not + required if the event type is ``refund``. + taxes (Sequence[google.cloud.recommendationengine_v1beta1.types.PurchaseTransaction.TaxesEntry]): + Optional. All the taxes associated with the + transaction. + costs (Sequence[google.cloud.recommendationengine_v1beta1.types.PurchaseTransaction.CostsEntry]): + Optional. All the costs associated with the product. These + can be manufacturing costs, shipping expenses not borne by + the end user, or any other costs. + + Total product cost such that profit = revenue - (sum(taxes) + + sum(costs)) If product_cost is not set, then profit = + revenue - tax - shipping - sum(CatalogItem.costs). + + If CatalogItem.cost is not specified for one of the items, + CatalogItem.cost based profit *cannot* be calculated for + this Transaction. + currency_code (str): + Required. Currency code. Use three-character ISO-4217 code. + This field is not required if the event type is ``refund``. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + revenue = proto.Field( + proto.FLOAT, + number=2, + ) + taxes = proto.MapField( + proto.STRING, + proto.FLOAT, + number=3, + ) + costs = proto.MapField( + proto.STRING, + proto.FLOAT, + number=4, + ) + currency_code = proto.Field( + proto.STRING, + number=6, + ) + + +class ProductDetail(proto.Message): + r"""Detailed product information associated with a user event. + Attributes: + id (str): + Required. Catalog item ID. UTF-8 encoded + string with a length limit of 128 characters. + currency_code (str): + Optional. Currency code for price/costs. Use + three-character ISO-4217 code. Required only if + originalPrice or displayPrice is set. + original_price (float): + Optional. Original price of the product. If + provided, this will override the original price + in Catalog for this product. + display_price (float): + Optional. Display price of the product (e.g. + discounted price). If provided, this will + override the display price in Catalog for this + product. + stock_state (google.cloud.recommendationengine_v1beta1.types.ProductCatalogItem.StockState): + Optional. Item stock state. If provided, this + overrides the stock state in Catalog for items + in this event. + quantity (int): + Optional. Quantity of the product associated with the user + event. For example, this field will be 2 if two products are + added to the shopping cart for ``add-to-cart`` event. + Required for ``add-to-cart``, ``add-to-list``, + ``remove-from-cart``, ``checkout-start``, + ``purchase-complete``, ``refund`` event types. + available_quantity (int): + Optional. Quantity of the products in stock when a user + event happens. Optional. If provided, this overrides the + available quantity in Catalog for this event. and can only + be set if ``stock_status`` is set to ``IN_STOCK``. + + Note that if an item is out of stock, you must set the + ``stock_state`` field to be ``OUT_OF_STOCK``. Leaving this + field unspecified / as zero is not sufficient to mark the + item out of stock. + item_attributes (google.cloud.recommendationengine_v1beta1.types.FeatureMap): + Optional. Extra features associated with a + product in the user event. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + currency_code = proto.Field( + proto.STRING, + number=2, + ) + original_price = proto.Field( + proto.FLOAT, + number=3, + ) + display_price = proto.Field( + proto.FLOAT, + number=4, + ) + stock_state = proto.Field( + proto.ENUM, + number=5, + enum=catalog.ProductCatalogItem.StockState, + ) + quantity = proto.Field( + proto.INT32, + number=6, + ) + available_quantity = proto.Field( + proto.INT32, + number=7, + ) + item_attributes = proto.Field( + proto.MESSAGE, + number=8, + message=common.FeatureMap, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/user_event_service.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/user_event_service.py new file mode 100644 index 00000000..27e37003 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/user_event_service.py @@ -0,0 +1,289 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.recommendationengine.v1beta1', + manifest={ + 'PurgeUserEventsRequest', + 'PurgeUserEventsMetadata', + 'PurgeUserEventsResponse', + 'WriteUserEventRequest', + 'CollectUserEventRequest', + 'ListUserEventsRequest', + 'ListUserEventsResponse', + }, +) + + +class PurgeUserEventsRequest(proto.Message): + r"""Request message for PurgeUserEvents method. + Attributes: + parent (str): + Required. The resource name of the event_store under which + the events are created. The format is + ``projects/${projectId}/locations/global/catalogs/${catalogId}/eventStores/${eventStoreId}`` + filter (str): + Required. The filter string to specify the events to be + deleted. Empty string filter is not allowed. This filter can + also be used with ListUserEvents API to list events that + will be deleted. The eligible fields for filtering are: + + - eventType - UserEvent.eventType field of type string. + - eventTime - in ISO 8601 "zulu" format. + - visitorId - field of type string. Specifying this will + delete all events associated with a visitor. + - userId - field of type string. Specifying this will + delete all events associated with a user. Example 1: + Deleting all events in a time range. + ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` + Example 2: Deleting specific eventType in time range. + ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` + Example 3: Deleting all events for a specific visitor + ``visitorId = visitor1024`` The filtering fields are + assumed to have an implicit AND. + force (bool): + Optional. The default value is false. + Override this flag to true to actually perform + the purge. If the field is not set to true, a + sampling of events to be deleted will be + returned. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + force = proto.Field( + proto.BOOL, + number=3, + ) + + +class PurgeUserEventsMetadata(proto.Message): + r"""Metadata related to the progress of the PurgeUserEvents + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + operation_name (str): + The ID of the request / operation. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + """ + + operation_name = proto.Field( + proto.STRING, + number=1, + ) + create_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class PurgeUserEventsResponse(proto.Message): + r"""Response of the PurgeUserEventsRequest. If the long running + operation is successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + Attributes: + purged_events_count (int): + The total count of events purged as a result + of the operation. + user_events_sample (Sequence[google.cloud.recommendationengine_v1beta1.types.UserEvent]): + A sampling of events deleted (or will be deleted) depending + on the ``force`` property in the request. Max of 500 items + will be returned. + """ + + purged_events_count = proto.Field( + proto.INT64, + number=1, + ) + user_events_sample = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=gcr_user_event.UserEvent, + ) + + +class WriteUserEventRequest(proto.Message): + r"""Request message for WriteUserEvent method. + Attributes: + parent (str): + Required. The parent eventStore resource name, such as + ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store``. + user_event (google.cloud.recommendationengine_v1beta1.types.UserEvent): + Required. User event to write. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_user_event.UserEvent, + ) + + +class CollectUserEventRequest(proto.Message): + r"""Request message for CollectUserEvent method. + Attributes: + parent (str): + Required. The parent eventStore name, such as + ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store``. + user_event (str): + Required. URL encoded UserEvent proto. + uri (str): + Optional. The url including cgi-parameters + but excluding the hash fragment. The URL must be + truncated to 1.5K bytes to conservatively be + under the 2K bytes. This is often more useful + than the referer url, because many browsers only + send the domain for 3rd party requests. + ets (int): + Optional. The event timestamp in + milliseconds. This prevents browser caching of + otherwise identical get requests. The name is + abbreviated to reduce the payload bytes. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + user_event = proto.Field( + proto.STRING, + number=2, + ) + uri = proto.Field( + proto.STRING, + number=3, + ) + ets = proto.Field( + proto.INT64, + number=4, + ) + + +class ListUserEventsRequest(proto.Message): + r"""Request message for ListUserEvents method. + Attributes: + parent (str): + Required. The parent eventStore resource name, such as + ``projects/*/locations/*/catalogs/default_catalog/eventStores/default_event_store``. + page_size (int): + Optional. Maximum number of results to return + per page. If zero, the service will choose a + reasonable default. + page_token (str): + Optional. The previous + ListUserEventsResponse.next_page_token. + filter (str): + Optional. Filtering expression to specify restrictions over + returned events. This is a sequence of terms, where each + term applies some kind of a restriction to the returned user + events. Use this expression to restrict results to a + specific time range, or filter events by eventType. eg: + eventTime > "2012-04-23T18:25:43.511Z" + eventsMissingCatalogItems + eventTime<"2012-04-23T18:25:43.511Z" eventType=search + + We expect only 3 types of fields: + + :: + + * eventTime: this can be specified a maximum of 2 times, once with a + less than operator and once with a greater than operator. The + eventTime restrict should result in one contiguous valid eventTime + range. + + * eventType: only 1 eventType restriction can be specified. + + * eventsMissingCatalogItems: specififying this will restrict results + to events for which catalog items were not found in the catalog. The + default behavior is to return only those events for which catalog + items were found. + + Some examples of valid filters expressions: + + - Example 1: eventTime > "2012-04-23T18:25:43.511Z" + eventTime < "2012-04-23T18:30:43.511Z" + - Example 2: eventTime > "2012-04-23T18:25:43.511Z" + eventType = detail-page-view + - Example 3: eventsMissingCatalogItems eventType = search + eventTime < "2018-04-23T18:30:43.511Z" + - Example 4: eventTime > "2012-04-23T18:25:43.511Z" + - Example 5: eventType = search + - Example 6: eventsMissingCatalogItems + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + + +class ListUserEventsResponse(proto.Message): + r"""Response message for ListUserEvents method. + Attributes: + user_events (Sequence[google.cloud.recommendationengine_v1beta1.types.UserEvent]): + The user events. + next_page_token (str): + If empty, the list is complete. If nonempty, the token to + pass to the next request's ListUserEvents.page_token. + """ + + @property + def raw_page(self): + return self + + user_events = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_user_event.UserEvent, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/mypy.ini b/owl-bot-staging/v1beta1/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/owl-bot-staging/v1beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1beta1/noxfile.py b/owl-bot-staging/v1beta1/noxfile.py new file mode 100644 index 00000000..4cb263a0 --- /dev/null +++ b/owl-bot-staging/v1beta1/noxfile.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", +] + +@nox.session(python=['3.6', '3.7', '3.8', '3.9']) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/recommendationengine_v1beta1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.7') +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=['3.6', '3.7']) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python='3.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) diff --git a/owl-bot-staging/v1beta1/scripts/fixup_recommendationengine_v1beta1_keywords.py b/owl-bot-staging/v1beta1/scripts/fixup_recommendationengine_v1beta1_keywords.py new file mode 100644 index 00000000..9652c971 --- /dev/null +++ b/owl-bot-staging/v1beta1/scripts/fixup_recommendationengine_v1beta1_keywords.py @@ -0,0 +1,190 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class recommendationengineCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), + 'create_catalog_item': ('parent', 'catalog_item', ), + 'create_prediction_api_key_registration': ('parent', 'prediction_api_key_registration', ), + 'delete_catalog_item': ('name', ), + 'delete_prediction_api_key_registration': ('name', ), + 'get_catalog_item': ('name', ), + 'import_catalog_items': ('parent', 'input_config', 'request_id', 'errors_config', ), + 'import_user_events': ('parent', 'input_config', 'request_id', 'errors_config', ), + 'list_catalog_items': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_prediction_api_key_registrations': ('parent', 'page_size', 'page_token', ), + 'list_user_events': ('parent', 'page_size', 'page_token', 'filter', ), + 'predict': ('name', 'user_event', 'page_size', 'page_token', 'filter', 'dry_run', 'params', 'labels', ), + 'purge_user_events': ('parent', 'filter', 'force', ), + 'update_catalog_item': ('name', 'catalog_item', 'update_mask', ), + 'write_user_event': ('parent', 'user_event', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=recommendationengineCallTransformer(), +): + """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 recommendationengine 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/v1beta1/setup.py b/owl-bot-staging/v1beta1/setup.py new file mode 100644 index 00000000..d9ec7adc --- /dev/null +++ b/owl-bot-staging/v1beta1/setup.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, 'README.rst') +with io.open(readme_filename, encoding='utf-8') as readme_file: + readme = readme_file.read() + +setuptools.setup( + name='google-cloud-recommendations-ai', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.27.0, < 2.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'packaging >= 14.3', ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v1beta1/tests/__init__.py b/owl-bot-staging/v1beta1/tests/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1beta1/tests/unit/__init__.py b/owl-bot-staging/v1beta1/tests/unit/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/__init__.py b/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_catalog_service.py b/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_catalog_service.py new file mode 100644 index 00000000..86ce00d3 --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_catalog_service.py @@ -0,0 +1,2676 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.recommendationengine_v1beta1.services.catalog_service import CatalogServiceAsyncClient +from google.cloud.recommendationengine_v1beta1.services.catalog_service import CatalogServiceClient +from google.cloud.recommendationengine_v1beta1.services.catalog_service import pagers +from google.cloud.recommendationengine_v1beta1.services.catalog_service import transports +from google.cloud.recommendationengine_v1beta1.services.catalog_service.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.recommendationengine_v1beta1.types import catalog +from google.cloud.recommendationengine_v1beta1.types import catalog_service +from google.cloud.recommendationengine_v1beta1.types import common +from google.cloud.recommendationengine_v1beta1.types import import_ +from google.cloud.recommendationengine_v1beta1.types import user_event +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CatalogServiceClient._get_default_mtls_endpoint(None) is None + assert CatalogServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CatalogServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + CatalogServiceClient, + CatalogServiceAsyncClient, +]) +def test_catalog_service_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'recommendationengine.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + CatalogServiceClient, + CatalogServiceAsyncClient, +]) +def test_catalog_service_client_service_account_always_use_jwt(client_class): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + client = client_class(credentials=creds) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CatalogServiceGrpcTransport, "grpc"), + (transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_catalog_service_client_service_account_always_use_jwt_true(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) + + +@pytest.mark.parametrize("client_class", [ + CatalogServiceClient, + CatalogServiceAsyncClient, +]) +def test_catalog_service_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'recommendationengine.googleapis.com:443' + + +def test_catalog_service_client_get_transport_class(): + transport = CatalogServiceClient.get_transport_class() + available_transports = [ + transports.CatalogServiceGrpcTransport, + ] + assert transport in available_transports + + transport = CatalogServiceClient.get_transport_class("grpc") + assert transport == transports.CatalogServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +def test_catalog_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(CatalogServiceClient, '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(CatalogServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "true"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "false"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) +@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_catalog_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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_catalog_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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_catalog_service_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_catalog_service_client_client_options_from_dict(): + with mock.patch('google.cloud.recommendationengine_v1beta1.services.catalog_service.transports.CatalogServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CatalogServiceClient( + 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, + ) + + +def test_create_catalog_item(transport: str = 'grpc', request_type=catalog_service.CreateCatalogItemRequest): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CatalogItem( + id='id_value', + title='title_value', + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + item_group_id='item_group_id_value', + product_metadata=catalog.ProductCatalogItem(exact_price=catalog.ProductCatalogItem.ExactPrice(display_price=0.1384)), + ) + response = client.create_catalog_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] == catalog_service.CreateCatalogItemRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CatalogItem) + assert response.id == 'id_value' + assert response.title == 'title_value' + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.item_group_id == 'item_group_id_value' + + +def test_create_catalog_item_from_dict(): + test_create_catalog_item(request_type=dict) + + +def test_create_catalog_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 = CatalogServiceClient( + credentials=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_catalog_item), + '__call__') as call: + client.create_catalog_item() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.CreateCatalogItemRequest() + + +@pytest.mark.asyncio +async def test_create_catalog_item_async(transport: str = 'grpc_asyncio', request_type=catalog_service.CreateCatalogItemRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem( + id='id_value', + title='title_value', + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + item_group_id='item_group_id_value', + )) + response = await client.create_catalog_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.CreateCatalogItemRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CatalogItem) + assert response.id == 'id_value' + assert response.title == 'title_value' + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.item_group_id == 'item_group_id_value' + + +@pytest.mark.asyncio +async def test_create_catalog_item_async_from_dict(): + await test_create_catalog_item_async(request_type=dict) + + +def test_create_catalog_item_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.CreateCatalogItemRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_catalog_item), + '__call__') as call: + call.return_value = catalog.CatalogItem() + client.create_catalog_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', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_catalog_item_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.CreateCatalogItemRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_catalog_item), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem()) + await client.create_catalog_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', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_create_catalog_item_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_catalog_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CatalogItem() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_catalog_item( + parent='parent_value', + catalog_item=catalog.CatalogItem(id='id_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].catalog_item == catalog.CatalogItem(id='id_value') + + +def test_create_catalog_item_flattened_error(): + client = CatalogServiceClient( + credentials=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_catalog_item( + catalog_service.CreateCatalogItemRequest(), + parent='parent_value', + catalog_item=catalog.CatalogItem(id='id_value'), + ) + + +@pytest.mark.asyncio +async def test_create_catalog_item_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_catalog_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CatalogItem() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_catalog_item( + parent='parent_value', + catalog_item=catalog.CatalogItem(id='id_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].catalog_item == catalog.CatalogItem(id='id_value') + + +@pytest.mark.asyncio +async def test_create_catalog_item_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_catalog_item( + catalog_service.CreateCatalogItemRequest(), + parent='parent_value', + catalog_item=catalog.CatalogItem(id='id_value'), + ) + + +def test_get_catalog_item(transport: str = 'grpc', request_type=catalog_service.GetCatalogItemRequest): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CatalogItem( + id='id_value', + title='title_value', + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + item_group_id='item_group_id_value', + product_metadata=catalog.ProductCatalogItem(exact_price=catalog.ProductCatalogItem.ExactPrice(display_price=0.1384)), + ) + response = client.get_catalog_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] == catalog_service.GetCatalogItemRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CatalogItem) + assert response.id == 'id_value' + assert response.title == 'title_value' + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.item_group_id == 'item_group_id_value' + + +def test_get_catalog_item_from_dict(): + test_get_catalog_item(request_type=dict) + + +def test_get_catalog_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 = CatalogServiceClient( + credentials=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_catalog_item), + '__call__') as call: + client.get_catalog_item() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetCatalogItemRequest() + + +@pytest.mark.asyncio +async def test_get_catalog_item_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetCatalogItemRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem( + id='id_value', + title='title_value', + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + item_group_id='item_group_id_value', + )) + response = await client.get_catalog_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetCatalogItemRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CatalogItem) + assert response.id == 'id_value' + assert response.title == 'title_value' + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.item_group_id == 'item_group_id_value' + + +@pytest.mark.asyncio +async def test_get_catalog_item_async_from_dict(): + await test_get_catalog_item_async(request_type=dict) + + +def test_get_catalog_item_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetCatalogItemRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_catalog_item), + '__call__') as call: + call.return_value = catalog.CatalogItem() + client.get_catalog_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', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_catalog_item_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.GetCatalogItemRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_catalog_item), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem()) + await client.get_catalog_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', + 'name=name/value', + ) in kw['metadata'] + + +def test_get_catalog_item_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_catalog_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CatalogItem() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_catalog_item( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_get_catalog_item_flattened_error(): + client = CatalogServiceClient( + credentials=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_catalog_item( + catalog_service.GetCatalogItemRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_catalog_item_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_catalog_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CatalogItem() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_catalog_item( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_catalog_item_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_catalog_item( + catalog_service.GetCatalogItemRequest(), + name='name_value', + ) + + +def test_list_catalog_items(transport: str = 'grpc', request_type=catalog_service.ListCatalogItemsRequest): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogItemsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_catalog_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] == catalog_service.ListCatalogItemsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogItemsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_catalog_items_from_dict(): + test_list_catalog_items(request_type=dict) + + +def test_list_catalog_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 = CatalogServiceClient( + credentials=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_catalog_items), + '__call__') as call: + client.list_catalog_items() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogItemsRequest() + + +@pytest.mark.asyncio +async def test_list_catalog_items_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ListCatalogItemsRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogItemsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_catalog_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogItemsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogItemsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_catalog_items_async_from_dict(): + await test_list_catalog_items_async(request_type=dict) + + +def test_list_catalog_items_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ListCatalogItemsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalog_items), + '__call__') as call: + call.return_value = catalog_service.ListCatalogItemsResponse() + client.list_catalog_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', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_catalog_items_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.ListCatalogItemsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalog_items), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogItemsResponse()) + await client.list_catalog_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', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_list_catalog_items_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalog_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogItemsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_catalog_items( + parent='parent_value', + filter='filter_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].filter == 'filter_value' + + +def test_list_catalog_items_flattened_error(): + client = CatalogServiceClient( + credentials=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_catalog_items( + catalog_service.ListCatalogItemsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +@pytest.mark.asyncio +async def test_list_catalog_items_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalog_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogItemsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogItemsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_catalog_items( + parent='parent_value', + filter='filter_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].filter == 'filter_value' + + +@pytest.mark.asyncio +async def test_list_catalog_items_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_catalog_items( + catalog_service.ListCatalogItemsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +def test_list_catalog_items_pager(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalog_items), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + catalog.CatalogItem(), + catalog.CatalogItem(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[], + next_page_token='def', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + catalog.CatalogItem(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_catalog_items(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, catalog.CatalogItem) + for i in results) + +def test_list_catalog_items_pages(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalog_items), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + catalog.CatalogItem(), + catalog.CatalogItem(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[], + next_page_token='def', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + catalog.CatalogItem(), + ], + ), + RuntimeError, + ) + pages = list(client.list_catalog_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_list_catalog_items_async_pager(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalog_items), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + catalog.CatalogItem(), + catalog.CatalogItem(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[], + next_page_token='def', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + catalog.CatalogItem(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_catalog_items(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, catalog.CatalogItem) + for i in responses) + +@pytest.mark.asyncio +async def test_list_catalog_items_async_pages(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalog_items), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + catalog.CatalogItem(), + catalog.CatalogItem(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[], + next_page_token='def', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + catalog.CatalogItem(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_catalog_items(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_update_catalog_item(transport: str = 'grpc', request_type=catalog_service.UpdateCatalogItemRequest): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CatalogItem( + id='id_value', + title='title_value', + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + item_group_id='item_group_id_value', + product_metadata=catalog.ProductCatalogItem(exact_price=catalog.ProductCatalogItem.ExactPrice(display_price=0.1384)), + ) + response = client.update_catalog_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] == catalog_service.UpdateCatalogItemRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CatalogItem) + assert response.id == 'id_value' + assert response.title == 'title_value' + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.item_group_id == 'item_group_id_value' + + +def test_update_catalog_item_from_dict(): + test_update_catalog_item(request_type=dict) + + +def test_update_catalog_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 = CatalogServiceClient( + credentials=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_catalog_item), + '__call__') as call: + client.update_catalog_item() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogItemRequest() + + +@pytest.mark.asyncio +async def test_update_catalog_item_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCatalogItemRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem( + id='id_value', + title='title_value', + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + item_group_id='item_group_id_value', + )) + response = await client.update_catalog_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogItemRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CatalogItem) + assert response.id == 'id_value' + assert response.title == 'title_value' + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.item_group_id == 'item_group_id_value' + + +@pytest.mark.asyncio +async def test_update_catalog_item_async_from_dict(): + await test_update_catalog_item_async(request_type=dict) + + +def test_update_catalog_item_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCatalogItemRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog_item), + '__call__') as call: + call.return_value = catalog.CatalogItem() + client.update_catalog_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', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_catalog_item_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.UpdateCatalogItemRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog_item), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem()) + await client.update_catalog_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', + 'name=name/value', + ) in kw['metadata'] + + +def test_update_catalog_item_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CatalogItem() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_catalog_item( + name='name_value', + catalog_item=catalog.CatalogItem(id='id_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + assert args[0].catalog_item == catalog.CatalogItem(id='id_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_catalog_item_flattened_error(): + client = CatalogServiceClient( + credentials=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_catalog_item( + catalog_service.UpdateCatalogItemRequest(), + name='name_value', + catalog_item=catalog.CatalogItem(id='id_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_catalog_item_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CatalogItem() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_catalog_item( + name='name_value', + catalog_item=catalog.CatalogItem(id='id_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + assert args[0].catalog_item == catalog.CatalogItem(id='id_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_catalog_item_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_catalog_item( + catalog_service.UpdateCatalogItemRequest(), + name='name_value', + catalog_item=catalog.CatalogItem(id='id_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_catalog_item(transport: str = 'grpc', request_type=catalog_service.DeleteCatalogItemRequest): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_catalog_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] == catalog_service.DeleteCatalogItemRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_catalog_item_from_dict(): + test_delete_catalog_item(request_type=dict) + + +def test_delete_catalog_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 = CatalogServiceClient( + credentials=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_catalog_item), + '__call__') as call: + client.delete_catalog_item() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.DeleteCatalogItemRequest() + + +@pytest.mark.asyncio +async def test_delete_catalog_item_async(transport: str = 'grpc_asyncio', request_type=catalog_service.DeleteCatalogItemRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_catalog_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.DeleteCatalogItemRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_catalog_item_async_from_dict(): + await test_delete_catalog_item_async(request_type=dict) + + +def test_delete_catalog_item_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.DeleteCatalogItemRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_catalog_item), + '__call__') as call: + call.return_value = None + client.delete_catalog_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', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_catalog_item_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = catalog_service.DeleteCatalogItemRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_catalog_item), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_catalog_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', + 'name=name/value', + ) in kw['metadata'] + + +def test_delete_catalog_item_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_catalog_item), + '__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_catalog_item( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_delete_catalog_item_flattened_error(): + client = CatalogServiceClient( + credentials=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_catalog_item( + catalog_service.DeleteCatalogItemRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_catalog_item_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_catalog_item), + '__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_catalog_item( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_delete_catalog_item_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_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_catalog_item( + catalog_service.DeleteCatalogItemRequest(), + name='name_value', + ) + + +def test_import_catalog_items(transport: str = 'grpc', request_type=import_.ImportCatalogItemsRequest): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_catalog_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] == import_.ImportCatalogItemsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_catalog_items_from_dict(): + test_import_catalog_items(request_type=dict) + + +def test_import_catalog_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 = CatalogServiceClient( + credentials=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_catalog_items), + '__call__') as call: + client.import_catalog_items() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_.ImportCatalogItemsRequest() + + +@pytest.mark.asyncio +async def test_import_catalog_items_async(transport: str = 'grpc_asyncio', request_type=import_.ImportCatalogItemsRequest): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_catalog_items), + '__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_catalog_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_.ImportCatalogItemsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_catalog_items_async_from_dict(): + await test_import_catalog_items_async(request_type=dict) + + +def test_import_catalog_items_field_headers(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_.ImportCatalogItemsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_catalog_items), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_catalog_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', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_import_catalog_items_field_headers_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_.ImportCatalogItemsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_catalog_items), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_catalog_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', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_import_catalog_items_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_catalog_items), + '__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.import_catalog_items( + parent='parent_value', + request_id='request_id_value', + input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), + errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].request_id == 'request_id_value' + assert args[0].input_config == import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])) + assert args[0].errors_config == import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value') + + +def test_import_catalog_items_flattened_error(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.import_catalog_items( + import_.ImportCatalogItemsRequest(), + parent='parent_value', + request_id='request_id_value', + input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), + errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), + ) + + +@pytest.mark.asyncio +async def test_import_catalog_items_flattened_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_catalog_items), + '__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.import_catalog_items( + parent='parent_value', + request_id='request_id_value', + input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), + errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].request_id == 'request_id_value' + assert args[0].input_config == import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])) + assert args[0].errors_config == import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value') + + +@pytest.mark.asyncio +async def test_import_catalog_items_flattened_error_async(): + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.import_catalog_items( + import_.ImportCatalogItemsRequest(), + parent='parent_value', + request_id='request_id_value', + input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), + errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CatalogServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CatalogServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CatalogServiceGrpcTransport, + ) + +def test_catalog_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CatalogServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_catalog_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.recommendationengine_v1beta1.services.catalog_service.transports.CatalogServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CatalogServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_catalog_item', + 'get_catalog_item', + 'list_catalog_items', + 'update_catalog_item', + 'delete_catalog_item', + 'import_catalog_items', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +def test_catalog_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.recommendationengine_v1beta1.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CatalogServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_catalog_service_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.recommendationengine_v1beta1.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CatalogServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + ), + quota_project_id="octopus", + ) + + +def test_catalog_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.recommendationengine_v1beta1.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CatalogServiceTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_catalog_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) + CatalogServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_catalog_service_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + CatalogServiceClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_catalog_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.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_catalog_service_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CatalogServiceGrpcTransport, grpc_helpers), + (transports.CatalogServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_catalog_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( + "recommendationengine.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="recommendationengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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_catalog_service_host_no_port(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='recommendationengine.googleapis.com'), + ) + assert client.transport._host == 'recommendationengine.googleapis.com:443' + + +def test_catalog_service_host_with_port(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='recommendationengine.googleapis.com:8000'), + ) + assert client.transport._host == 'recommendationengine.googleapis.com:8000' + +def test_catalog_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CatalogServiceGrpcTransport( + 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_catalog_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CatalogServiceGrpcAsyncIOTransport( + 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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) +def test_catalog_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_catalog_service_grpc_lro_client(): + client = CatalogServiceClient( + 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_catalog_service_grpc_lro_async_client(): + client = CatalogServiceAsyncClient( + 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_catalog_path(): + project = "squid" + location = "clam" + catalog = "whelk" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) + actual = CatalogServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = CatalogServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_catalog_item_path_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/catalogItems/{catalog_item_path=**}".format(project=project, location=location, catalog=catalog, ) + actual = CatalogServiceClient.catalog_item_path_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_item_path_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "catalog": "abalone", + } + path = CatalogServiceClient.catalog_item_path_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_catalog_item_path_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CatalogServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = CatalogServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = CatalogServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = CatalogServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CatalogServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = CatalogServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = CatalogServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = CatalogServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.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 = CatalogServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = CatalogServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.CatalogServiceTransport, '_prep_wrapped_messages') as prep: + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CatalogServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CatalogServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_api_key_registry.py b/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_api_key_registry.py new file mode 100644 index 00000000..e44ce0ee --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_api_key_registry.py @@ -0,0 +1,1840 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry import PredictionApiKeyRegistryAsyncClient +from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry import PredictionApiKeyRegistryClient +from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry import pagers +from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry import transports +from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.recommendationengine_v1beta1.types import prediction_apikey_registry_service +from google.oauth2 import service_account +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert PredictionApiKeyRegistryClient._get_default_mtls_endpoint(None) is None + assert PredictionApiKeyRegistryClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert PredictionApiKeyRegistryClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert PredictionApiKeyRegistryClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert PredictionApiKeyRegistryClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert PredictionApiKeyRegistryClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + PredictionApiKeyRegistryClient, + PredictionApiKeyRegistryAsyncClient, +]) +def test_prediction_api_key_registry_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'recommendationengine.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + PredictionApiKeyRegistryClient, + PredictionApiKeyRegistryAsyncClient, +]) +def test_prediction_api_key_registry_client_service_account_always_use_jwt(client_class): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + client = client_class(credentials=creds) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.PredictionApiKeyRegistryGrpcTransport, "grpc"), + (transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_prediction_api_key_registry_client_service_account_always_use_jwt_true(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) + + +@pytest.mark.parametrize("client_class", [ + PredictionApiKeyRegistryClient, + PredictionApiKeyRegistryAsyncClient, +]) +def test_prediction_api_key_registry_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'recommendationengine.googleapis.com:443' + + +def test_prediction_api_key_registry_client_get_transport_class(): + transport = PredictionApiKeyRegistryClient.get_transport_class() + available_transports = [ + transports.PredictionApiKeyRegistryGrpcTransport, + ] + assert transport in available_transports + + transport = PredictionApiKeyRegistryClient.get_transport_class("grpc") + assert transport == transports.PredictionApiKeyRegistryGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PredictionApiKeyRegistryClient, transports.PredictionApiKeyRegistryGrpcTransport, "grpc"), + (PredictionApiKeyRegistryAsyncClient, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(PredictionApiKeyRegistryClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionApiKeyRegistryClient)) +@mock.patch.object(PredictionApiKeyRegistryAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionApiKeyRegistryAsyncClient)) +def test_prediction_api_key_registry_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(PredictionApiKeyRegistryClient, '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(PredictionApiKeyRegistryClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (PredictionApiKeyRegistryClient, transports.PredictionApiKeyRegistryGrpcTransport, "grpc", "true"), + (PredictionApiKeyRegistryAsyncClient, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (PredictionApiKeyRegistryClient, transports.PredictionApiKeyRegistryGrpcTransport, "grpc", "false"), + (PredictionApiKeyRegistryAsyncClient, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(PredictionApiKeyRegistryClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionApiKeyRegistryClient)) +@mock.patch.object(PredictionApiKeyRegistryAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionApiKeyRegistryAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_prediction_api_key_registry_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PredictionApiKeyRegistryClient, transports.PredictionApiKeyRegistryGrpcTransport, "grpc"), + (PredictionApiKeyRegistryAsyncClient, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_prediction_api_key_registry_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PredictionApiKeyRegistryClient, transports.PredictionApiKeyRegistryGrpcTransport, "grpc"), + (PredictionApiKeyRegistryAsyncClient, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_prediction_api_key_registry_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_prediction_api_key_registry_client_client_options_from_dict(): + with mock.patch('google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry.transports.PredictionApiKeyRegistryGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = PredictionApiKeyRegistryClient( + 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, + ) + + +def test_create_prediction_api_key_registration(transport: str = 'grpc', request_type=prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_prediction_api_key_registration), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = prediction_apikey_registry_service.PredictionApiKeyRegistration( + api_key='api_key_value', + ) + response = client.create_prediction_api_key_registration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, prediction_apikey_registry_service.PredictionApiKeyRegistration) + assert response.api_key == 'api_key_value' + + +def test_create_prediction_api_key_registration_from_dict(): + test_create_prediction_api_key_registration(request_type=dict) + + +def test_create_prediction_api_key_registration_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PredictionApiKeyRegistryClient( + credentials=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_prediction_api_key_registration), + '__call__') as call: + client.create_prediction_api_key_registration() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() + + +@pytest.mark.asyncio +async def test_create_prediction_api_key_registration_async(transport: str = 'grpc_asyncio', request_type=prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_prediction_api_key_registration), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(prediction_apikey_registry_service.PredictionApiKeyRegistration( + api_key='api_key_value', + )) + response = await client.create_prediction_api_key_registration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, prediction_apikey_registry_service.PredictionApiKeyRegistration) + assert response.api_key == 'api_key_value' + + +@pytest.mark.asyncio +async def test_create_prediction_api_key_registration_async_from_dict(): + await test_create_prediction_api_key_registration_async(request_type=dict) + + +def test_create_prediction_api_key_registration_field_headers(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_prediction_api_key_registration), + '__call__') as call: + call.return_value = prediction_apikey_registry_service.PredictionApiKeyRegistration() + client.create_prediction_api_key_registration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_prediction_api_key_registration_field_headers_async(): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_prediction_api_key_registration), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_apikey_registry_service.PredictionApiKeyRegistration()) + await client.create_prediction_api_key_registration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_prediction_api_key_registration_flattened(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_prediction_api_key_registration), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = prediction_apikey_registry_service.PredictionApiKeyRegistration() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_prediction_api_key_registration( + parent='parent_value', + prediction_api_key_registration=prediction_apikey_registry_service.PredictionApiKeyRegistration(api_key='api_key_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].prediction_api_key_registration == prediction_apikey_registry_service.PredictionApiKeyRegistration(api_key='api_key_value') + + +def test_create_prediction_api_key_registration_flattened_error(): + client = PredictionApiKeyRegistryClient( + credentials=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_prediction_api_key_registration( + prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest(), + parent='parent_value', + prediction_api_key_registration=prediction_apikey_registry_service.PredictionApiKeyRegistration(api_key='api_key_value'), + ) + + +@pytest.mark.asyncio +async def test_create_prediction_api_key_registration_flattened_async(): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_prediction_api_key_registration), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = prediction_apikey_registry_service.PredictionApiKeyRegistration() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_apikey_registry_service.PredictionApiKeyRegistration()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_prediction_api_key_registration( + parent='parent_value', + prediction_api_key_registration=prediction_apikey_registry_service.PredictionApiKeyRegistration(api_key='api_key_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].prediction_api_key_registration == prediction_apikey_registry_service.PredictionApiKeyRegistration(api_key='api_key_value') + + +@pytest.mark.asyncio +async def test_create_prediction_api_key_registration_flattened_error_async(): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_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_prediction_api_key_registration( + prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest(), + parent='parent_value', + prediction_api_key_registration=prediction_apikey_registry_service.PredictionApiKeyRegistration(api_key='api_key_value'), + ) + + +def test_list_prediction_api_key_registrations(transport: str = 'grpc', request_type=prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_prediction_api_key_registrations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_prediction_api_key_registrations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPredictionApiKeyRegistrationsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_prediction_api_key_registrations_from_dict(): + test_list_prediction_api_key_registrations(request_type=dict) + + +def test_list_prediction_api_key_registrations_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PredictionApiKeyRegistryClient( + credentials=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_prediction_api_key_registrations), + '__call__') as call: + client.list_prediction_api_key_registrations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() + + +@pytest.mark.asyncio +async def test_list_prediction_api_key_registrations_async(transport: str = 'grpc_asyncio', request_type=prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_prediction_api_key_registrations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_prediction_api_key_registrations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPredictionApiKeyRegistrationsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_prediction_api_key_registrations_async_from_dict(): + await test_list_prediction_api_key_registrations_async(request_type=dict) + + +def test_list_prediction_api_key_registrations_field_headers(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_prediction_api_key_registrations), + '__call__') as call: + call.return_value = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse() + client.list_prediction_api_key_registrations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_prediction_api_key_registrations_field_headers_async(): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_prediction_api_key_registrations), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse()) + await client.list_prediction_api_key_registrations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_prediction_api_key_registrations_flattened(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_prediction_api_key_registrations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_prediction_api_key_registrations( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +def test_list_prediction_api_key_registrations_flattened_error(): + client = PredictionApiKeyRegistryClient( + credentials=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_prediction_api_key_registrations( + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_prediction_api_key_registrations_flattened_async(): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_prediction_api_key_registrations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_prediction_api_key_registrations( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_prediction_api_key_registrations_flattened_error_async(): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_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_prediction_api_key_registrations( + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest(), + parent='parent_value', + ) + + +def test_list_prediction_api_key_registrations_pager(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_prediction_api_key_registrations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + next_page_token='abc', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[], + next_page_token='def', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + next_page_token='ghi', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_prediction_api_key_registrations(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, prediction_apikey_registry_service.PredictionApiKeyRegistration) + for i in results) + +def test_list_prediction_api_key_registrations_pages(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_prediction_api_key_registrations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + next_page_token='abc', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[], + next_page_token='def', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + next_page_token='ghi', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + ), + RuntimeError, + ) + pages = list(client.list_prediction_api_key_registrations(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_prediction_api_key_registrations_async_pager(): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_prediction_api_key_registrations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + next_page_token='abc', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[], + next_page_token='def', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + next_page_token='ghi', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_prediction_api_key_registrations(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, prediction_apikey_registry_service.PredictionApiKeyRegistration) + for i in responses) + +@pytest.mark.asyncio +async def test_list_prediction_api_key_registrations_async_pages(): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_prediction_api_key_registrations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + next_page_token='abc', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[], + next_page_token='def', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + next_page_token='ghi', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_prediction_api_key_registrations(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_delete_prediction_api_key_registration(transport: str = 'grpc', request_type=prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_prediction_api_key_registration), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_prediction_api_key_registration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_prediction_api_key_registration_from_dict(): + test_delete_prediction_api_key_registration(request_type=dict) + + +def test_delete_prediction_api_key_registration_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PredictionApiKeyRegistryClient( + credentials=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_prediction_api_key_registration), + '__call__') as call: + client.delete_prediction_api_key_registration() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() + + +@pytest.mark.asyncio +async def test_delete_prediction_api_key_registration_async(transport: str = 'grpc_asyncio', request_type=prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_prediction_api_key_registration), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_prediction_api_key_registration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_prediction_api_key_registration_async_from_dict(): + await test_delete_prediction_api_key_registration_async(request_type=dict) + + +def test_delete_prediction_api_key_registration_field_headers(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_prediction_api_key_registration), + '__call__') as call: + call.return_value = None + client.delete_prediction_api_key_registration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_prediction_api_key_registration_field_headers_async(): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_prediction_api_key_registration), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_prediction_api_key_registration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_prediction_api_key_registration_flattened(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_prediction_api_key_registration), + '__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_prediction_api_key_registration( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_delete_prediction_api_key_registration_flattened_error(): + client = PredictionApiKeyRegistryClient( + credentials=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_prediction_api_key_registration( + prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_prediction_api_key_registration_flattened_async(): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_prediction_api_key_registration), + '__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_prediction_api_key_registration( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_delete_prediction_api_key_registration_flattened_error_async(): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_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_prediction_api_key_registration( + prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PredictionApiKeyRegistryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PredictionApiKeyRegistryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionApiKeyRegistryClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PredictionApiKeyRegistryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionApiKeyRegistryClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PredictionApiKeyRegistryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PredictionApiKeyRegistryClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.PredictionApiKeyRegistryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.PredictionApiKeyRegistryGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.PredictionApiKeyRegistryGrpcTransport, + transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PredictionApiKeyRegistryGrpcTransport, + ) + +def test_prediction_api_key_registry_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PredictionApiKeyRegistryTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_prediction_api_key_registry_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry.transports.PredictionApiKeyRegistryTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.PredictionApiKeyRegistryTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_prediction_api_key_registration', + 'list_prediction_api_key_registrations', + 'delete_prediction_api_key_registration', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_prediction_api_key_registry_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.recommendationengine_v1beta1.services.prediction_api_key_registry.transports.PredictionApiKeyRegistryTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PredictionApiKeyRegistryTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_prediction_api_key_registry_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry.transports.PredictionApiKeyRegistryTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PredictionApiKeyRegistryTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + ), + quota_project_id="octopus", + ) + + +def test_prediction_api_key_registry_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.recommendationengine_v1beta1.services.prediction_api_key_registry.transports.PredictionApiKeyRegistryTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PredictionApiKeyRegistryTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_prediction_api_key_registry_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) + PredictionApiKeyRegistryClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_prediction_api_key_registry_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + PredictionApiKeyRegistryClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.PredictionApiKeyRegistryGrpcTransport, + transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_prediction_api_key_registry_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.PredictionApiKeyRegistryGrpcTransport, + transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_prediction_api_key_registry_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.PredictionApiKeyRegistryGrpcTransport, grpc_helpers), + (transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_prediction_api_key_registry_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( + "recommendationengine.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="recommendationengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.PredictionApiKeyRegistryGrpcTransport, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport]) +def test_prediction_api_key_registry_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_prediction_api_key_registry_host_no_port(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='recommendationengine.googleapis.com'), + ) + assert client.transport._host == 'recommendationengine.googleapis.com:443' + + +def test_prediction_api_key_registry_host_with_port(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='recommendationengine.googleapis.com:8000'), + ) + assert client.transport._host == 'recommendationengine.googleapis.com:8000' + +def test_prediction_api_key_registry_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PredictionApiKeyRegistryGrpcTransport( + 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_prediction_api_key_registry_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PredictionApiKeyRegistryGrpcAsyncIOTransport( + 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.PredictionApiKeyRegistryGrpcTransport, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport]) +def test_prediction_api_key_registry_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.PredictionApiKeyRegistryGrpcTransport, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport]) +def test_prediction_api_key_registry_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_event_store_path(): + project = "squid" + location = "clam" + catalog = "whelk" + event_store = "octopus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}".format(project=project, location=location, catalog=catalog, event_store=event_store, ) + actual = PredictionApiKeyRegistryClient.event_store_path(project, location, catalog, event_store) + assert expected == actual + + +def test_parse_event_store_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "catalog": "cuttlefish", + "event_store": "mussel", + } + path = PredictionApiKeyRegistryClient.event_store_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionApiKeyRegistryClient.parse_event_store_path(path) + assert expected == actual + +def test_prediction_api_key_registration_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + event_store = "abalone" + prediction_api_key_registration = "squid" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}/predictionApiKeyRegistrations/{prediction_api_key_registration}".format(project=project, location=location, catalog=catalog, event_store=event_store, prediction_api_key_registration=prediction_api_key_registration, ) + actual = PredictionApiKeyRegistryClient.prediction_api_key_registration_path(project, location, catalog, event_store, prediction_api_key_registration) + assert expected == actual + + +def test_parse_prediction_api_key_registration_path(): + expected = { + "project": "clam", + "location": "whelk", + "catalog": "octopus", + "event_store": "oyster", + "prediction_api_key_registration": "nudibranch", + } + path = PredictionApiKeyRegistryClient.prediction_api_key_registration_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionApiKeyRegistryClient.parse_prediction_api_key_registration_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = PredictionApiKeyRegistryClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = PredictionApiKeyRegistryClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionApiKeyRegistryClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = PredictionApiKeyRegistryClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = PredictionApiKeyRegistryClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionApiKeyRegistryClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = PredictionApiKeyRegistryClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = PredictionApiKeyRegistryClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionApiKeyRegistryClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = PredictionApiKeyRegistryClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = PredictionApiKeyRegistryClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionApiKeyRegistryClient.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 = PredictionApiKeyRegistryClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = PredictionApiKeyRegistryClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionApiKeyRegistryClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.PredictionApiKeyRegistryTransport, '_prep_wrapped_messages') as prep: + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.PredictionApiKeyRegistryTransport, '_prep_wrapped_messages') as prep: + transport_class = PredictionApiKeyRegistryClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py b/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py new file mode 100644 index 00000000..b5583b15 --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py @@ -0,0 +1,1377 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.recommendationengine_v1beta1.services.prediction_service import PredictionServiceAsyncClient +from google.cloud.recommendationengine_v1beta1.services.prediction_service import PredictionServiceClient +from google.cloud.recommendationengine_v1beta1.services.prediction_service import pagers +from google.cloud.recommendationengine_v1beta1.services.prediction_service import transports +from google.cloud.recommendationengine_v1beta1.services.prediction_service.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.recommendationengine_v1beta1.types import catalog +from google.cloud.recommendationengine_v1beta1.types import common +from google.cloud.recommendationengine_v1beta1.types import prediction_service +from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event +from google.oauth2 import service_account +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert PredictionServiceClient._get_default_mtls_endpoint(None) is None + assert PredictionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert PredictionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + PredictionServiceClient, + PredictionServiceAsyncClient, +]) +def test_prediction_service_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'recommendationengine.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + PredictionServiceClient, + PredictionServiceAsyncClient, +]) +def test_prediction_service_client_service_account_always_use_jwt(client_class): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + client = client_class(credentials=creds) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.PredictionServiceGrpcTransport, "grpc"), + (transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_prediction_service_client_service_account_always_use_jwt_true(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) + + +@pytest.mark.parametrize("client_class", [ + PredictionServiceClient, + PredictionServiceAsyncClient, +]) +def test_prediction_service_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'recommendationengine.googleapis.com:443' + + +def test_prediction_service_client_get_transport_class(): + transport = PredictionServiceClient.get_transport_class() + available_transports = [ + transports.PredictionServiceGrpcTransport, + ] + assert transport in available_transports + + transport = PredictionServiceClient.get_transport_class("grpc") + assert transport == transports.PredictionServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +def test_prediction_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(PredictionServiceClient, '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(PredictionServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "true"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "false"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) +@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_prediction_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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_prediction_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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), + (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_prediction_service_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_prediction_service_client_client_options_from_dict(): + with mock.patch('google.cloud.recommendationengine_v1beta1.services.prediction_service.transports.PredictionServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = PredictionServiceClient( + 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, + ) + + +def test_predict(transport: str = 'grpc', request_type=prediction_service.PredictRequest): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = prediction_service.PredictResponse( + recommendation_token='recommendation_token_value', + items_missing_in_catalog=['items_missing_in_catalog_value'], + dry_run=True, + next_page_token='next_page_token_value', + ) + response = client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.PredictPager) + assert response.recommendation_token == 'recommendation_token_value' + assert response.items_missing_in_catalog == ['items_missing_in_catalog_value'] + assert response.dry_run is True + assert response.next_page_token == 'next_page_token_value' + + +def test_predict_from_dict(): + test_predict(request_type=dict) + + +def test_predict_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + client.predict() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + + +@pytest.mark.asyncio +async def test_predict_async(transport: str = 'grpc_asyncio', request_type=prediction_service.PredictRequest): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse( + recommendation_token='recommendation_token_value', + items_missing_in_catalog=['items_missing_in_catalog_value'], + dry_run=True, + next_page_token='next_page_token_value', + )) + response = await client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_service.PredictRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.PredictAsyncPager) + assert response.recommendation_token == 'recommendation_token_value' + assert response.items_missing_in_catalog == ['items_missing_in_catalog_value'] + assert response.dry_run is True + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_predict_async_from_dict(): + await test_predict_async(request_type=dict) + + +def test_predict_field_headers(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = prediction_service.PredictRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + call.return_value = prediction_service.PredictResponse() + client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_predict_field_headers_async(): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = prediction_service.PredictRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse()) + await client.predict(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_predict_flattened(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = prediction_service.PredictResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.predict( + name='name_value', + user_event=gcr_user_event.UserEvent(event_type='event_type_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + assert args[0].user_event == gcr_user_event.UserEvent(event_type='event_type_value') + + +def test_predict_flattened_error(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.predict( + prediction_service.PredictRequest(), + name='name_value', + user_event=gcr_user_event.UserEvent(event_type='event_type_value'), + ) + + +@pytest.mark.asyncio +async def test_predict_flattened_async(): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = prediction_service.PredictResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.predict( + name='name_value', + user_event=gcr_user_event.UserEvent(event_type='event_type_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + assert args[0].user_event == gcr_user_event.UserEvent(event_type='event_type_value') + + +@pytest.mark.asyncio +async def test_predict_flattened_error_async(): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.predict( + prediction_service.PredictRequest(), + name='name_value', + user_event=gcr_user_event.UserEvent(event_type='event_type_value'), + ) + + +def test_predict_pager(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + ], + next_page_token='abc', + ), + prediction_service.PredictResponse( + results=[], + next_page_token='def', + ), + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + ], + next_page_token='ghi', + ), + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('name', ''), + )), + ) + pager = client.predict(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, prediction_service.PredictResponse.PredictionResult) + for i in results) + +def test_predict_pages(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + ], + next_page_token='abc', + ), + prediction_service.PredictResponse( + results=[], + next_page_token='def', + ), + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + ], + next_page_token='ghi', + ), + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + ], + ), + RuntimeError, + ) + pages = list(client.predict(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_predict_async_pager(): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + ], + next_page_token='abc', + ), + prediction_service.PredictResponse( + results=[], + next_page_token='def', + ), + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + ], + next_page_token='ghi', + ), + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.predict(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, prediction_service.PredictResponse.PredictionResult) + for i in responses) + +@pytest.mark.asyncio +async def test_predict_async_pages(): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + ], + next_page_token='abc', + ), + prediction_service.PredictResponse( + results=[], + next_page_token='def', + ), + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + ], + next_page_token='ghi', + ), + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.predict(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PredictionServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.PredictionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PredictionServiceGrpcTransport, + ) + +def test_prediction_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PredictionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_prediction_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.recommendationengine_v1beta1.services.prediction_service.transports.PredictionServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.PredictionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'predict', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_prediction_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.recommendationengine_v1beta1.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PredictionServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_prediction_service_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.recommendationengine_v1beta1.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PredictionServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + ), + quota_project_id="octopus", + ) + + +def test_prediction_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.recommendationengine_v1beta1.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PredictionServiceTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_prediction_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) + PredictionServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_prediction_service_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + PredictionServiceClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_prediction_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.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_prediction_service_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.PredictionServiceGrpcTransport, grpc_helpers), + (transports.PredictionServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_prediction_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( + "recommendationengine.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="recommendationengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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_prediction_service_host_no_port(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='recommendationengine.googleapis.com'), + ) + assert client.transport._host == 'recommendationengine.googleapis.com:443' + + +def test_prediction_service_host_with_port(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='recommendationengine.googleapis.com:8000'), + ) + assert client.transport._host == 'recommendationengine.googleapis.com:8000' + +def test_prediction_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PredictionServiceGrpcTransport( + 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_prediction_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PredictionServiceGrpcAsyncIOTransport( + 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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) +def test_prediction_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_placement_path(): + project = "squid" + location = "clam" + catalog = "whelk" + event_store = "octopus" + placement = "oyster" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}/placements/{placement}".format(project=project, location=location, catalog=catalog, event_store=event_store, placement=placement, ) + actual = PredictionServiceClient.placement_path(project, location, catalog, event_store, placement) + assert expected == actual + + +def test_parse_placement_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "catalog": "mussel", + "event_store": "winkle", + "placement": "nautilus", + } + path = PredictionServiceClient.placement_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_placement_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = PredictionServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = PredictionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = PredictionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = PredictionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = PredictionServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = PredictionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = PredictionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = PredictionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.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 = PredictionServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = PredictionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.PredictionServiceTransport, '_prep_wrapped_messages') as prep: + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.PredictionServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = PredictionServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_user_event_service.py b/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_user_event_service.py new file mode 100644 index 00000000..411b1828 --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_user_event_service.py @@ -0,0 +1,2394 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.recommendationengine_v1beta1.services.user_event_service import UserEventServiceAsyncClient +from google.cloud.recommendationengine_v1beta1.services.user_event_service import UserEventServiceClient +from google.cloud.recommendationengine_v1beta1.services.user_event_service import pagers +from google.cloud.recommendationengine_v1beta1.services.user_event_service import transports +from google.cloud.recommendationengine_v1beta1.services.user_event_service.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.recommendationengine_v1beta1.types import catalog +from google.cloud.recommendationengine_v1beta1.types import common +from google.cloud.recommendationengine_v1beta1.types import import_ +from google.cloud.recommendationengine_v1beta1.types import user_event +from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event +from google.cloud.recommendationengine_v1beta1.types import user_event_service +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert UserEventServiceClient._get_default_mtls_endpoint(None) is None + assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + UserEventServiceClient, + UserEventServiceAsyncClient, +]) +def test_user_event_service_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'recommendationengine.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + UserEventServiceClient, + UserEventServiceAsyncClient, +]) +def test_user_event_service_client_service_account_always_use_jwt(client_class): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + client = client_class(credentials=creds) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.UserEventServiceGrpcTransport, "grpc"), + (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_user_event_service_client_service_account_always_use_jwt_true(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) + + +@pytest.mark.parametrize("client_class", [ + UserEventServiceClient, + UserEventServiceAsyncClient, +]) +def test_user_event_service_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'recommendationengine.googleapis.com:443' + + +def test_user_event_service_client_get_transport_class(): + transport = UserEventServiceClient.get_transport_class() + available_transports = [ + transports.UserEventServiceGrpcTransport, + ] + assert transport in available_transports + + transport = UserEventServiceClient.get_transport_class("grpc") + assert transport == transports.UserEventServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_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(UserEventServiceClient, '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(UserEventServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_user_event_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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_user_event_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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_user_event_service_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_user_event_service_client_client_options_from_dict(): + with mock.patch('google.cloud.recommendationengine_v1beta1.services.user_event_service.transports.UserEventServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = UserEventServiceClient( + 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, + ) + + +def test_write_user_event(transport: str = 'grpc', request_type=user_event_service.WriteUserEventRequest): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_user_event.UserEvent( + event_type='event_type_value', + event_source=gcr_user_event.UserEvent.EventSource.AUTOML, + ) + response = client.write_user_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] == user_event_service.WriteUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.event_source == gcr_user_event.UserEvent.EventSource.AUTOML + + +def test_write_user_event_from_dict(): + test_write_user_event(request_type=dict) + + +def test_write_user_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 = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + client.write_user_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + + +@pytest.mark.asyncio +async def test_write_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.WriteUserEventRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_user_event.UserEvent( + event_type='event_type_value', + event_source=gcr_user_event.UserEvent.EventSource.AUTOML, + )) + response = await client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.event_source == gcr_user_event.UserEvent.EventSource.AUTOML + + +@pytest.mark.asyncio +async def test_write_user_event_async_from_dict(): + await test_write_user_event_async(request_type=dict) + + +def test_write_user_event_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.WriteUserEventRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + call.return_value = gcr_user_event.UserEvent() + client.write_user_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_write_user_event_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.WriteUserEventRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_user_event.UserEvent()) + await client.write_user_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_write_user_event_flattened(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_user_event.UserEvent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.write_user_event( + parent='parent_value', + user_event=gcr_user_event.UserEvent(event_type='event_type_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].user_event == gcr_user_event.UserEvent(event_type='event_type_value') + + +def test_write_user_event_flattened_error(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.write_user_event( + user_event_service.WriteUserEventRequest(), + parent='parent_value', + user_event=gcr_user_event.UserEvent(event_type='event_type_value'), + ) + + +@pytest.mark.asyncio +async def test_write_user_event_flattened_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_user_event.UserEvent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_user_event.UserEvent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.write_user_event( + parent='parent_value', + user_event=gcr_user_event.UserEvent(event_type='event_type_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].user_event == gcr_user_event.UserEvent(event_type='event_type_value') + + +@pytest.mark.asyncio +async def test_write_user_event_flattened_error_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.write_user_event( + user_event_service.WriteUserEventRequest(), + parent='parent_value', + user_event=gcr_user_event.UserEvent(event_type='event_type_value'), + ) + + +def test_collect_user_event(transport: str = 'grpc', request_type=user_event_service.CollectUserEventRequest): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + ) + response = client.collect_user_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] == user_event_service.CollectUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +def test_collect_user_event_from_dict(): + test_collect_user_event(request_type=dict) + + +def test_collect_user_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 = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + client.collect_user_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + + +@pytest.mark.asyncio +async def test_collect_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.CollectUserEventRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + )) + response = await client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +@pytest.mark.asyncio +async def test_collect_user_event_async_from_dict(): + await test_collect_user_event_async(request_type=dict) + + +def test_collect_user_event_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.CollectUserEventRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + call.return_value = httpbody_pb2.HttpBody() + client.collect_user_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_collect_user_event_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.CollectUserEventRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) + await client.collect_user_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_collect_user_event_flattened(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = httpbody_pb2.HttpBody() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.collect_user_event( + parent='parent_value', + user_event='user_event_value', + uri='uri_value', + ets=332, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].user_event == 'user_event_value' + assert args[0].uri == 'uri_value' + assert args[0].ets == 332 + + +def test_collect_user_event_flattened_error(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.collect_user_event( + user_event_service.CollectUserEventRequest(), + parent='parent_value', + user_event='user_event_value', + uri='uri_value', + ets=332, + ) + + +@pytest.mark.asyncio +async def test_collect_user_event_flattened_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = httpbody_pb2.HttpBody() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.collect_user_event( + parent='parent_value', + user_event='user_event_value', + uri='uri_value', + ets=332, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].user_event == 'user_event_value' + assert args[0].uri == 'uri_value' + assert args[0].ets == 332 + + +@pytest.mark.asyncio +async def test_collect_user_event_flattened_error_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.collect_user_event( + user_event_service.CollectUserEventRequest(), + parent='parent_value', + user_event='user_event_value', + uri='uri_value', + ets=332, + ) + + +def test_list_user_events(transport: str = 'grpc', request_type=user_event_service.ListUserEventsRequest): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user_event_service.ListUserEventsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_user_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] == user_event_service.ListUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUserEventsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_user_events_from_dict(): + test_list_user_events(request_type=dict) + + +def test_list_user_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 = UserEventServiceClient( + credentials=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_user_events), + '__call__') as call: + client.list_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.ListUserEventsRequest() + + +@pytest.mark.asyncio +async def test_list_user_events_async(transport: str = 'grpc_asyncio', request_type=user_event_service.ListUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event_service.ListUserEventsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.ListUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUserEventsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_user_events_async_from_dict(): + await test_list_user_events_async(request_type=dict) + + +def test_list_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.ListUserEventsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_events), + '__call__') as call: + call.return_value = user_event_service.ListUserEventsResponse() + client.list_user_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_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.ListUserEventsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event_service.ListUserEventsResponse()) + await client.list_user_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_user_events_flattened(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user_event_service.ListUserEventsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_user_events( + parent='parent_value', + filter='filter_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].filter == 'filter_value' + + +def test_list_user_events_flattened_error(): + client = UserEventServiceClient( + credentials=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_user_events( + user_event_service.ListUserEventsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +@pytest.mark.asyncio +async def test_list_user_events_flattened_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user_event_service.ListUserEventsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event_service.ListUserEventsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_user_events( + parent='parent_value', + filter='filter_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].filter == 'filter_value' + + +@pytest.mark.asyncio +async def test_list_user_events_flattened_error_async(): + client = UserEventServiceAsyncClient( + credentials=ga_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_user_events( + user_event_service.ListUserEventsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +def test_list_user_events_pager(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_events), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + user_event.UserEvent(), + user_event.UserEvent(), + ], + next_page_token='abc', + ), + user_event_service.ListUserEventsResponse( + user_events=[], + next_page_token='def', + ), + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + ], + next_page_token='ghi', + ), + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + user_event.UserEvent(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_user_events(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, user_event.UserEvent) + for i in results) + +def test_list_user_events_pages(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_events), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + user_event.UserEvent(), + user_event.UserEvent(), + ], + next_page_token='abc', + ), + user_event_service.ListUserEventsResponse( + user_events=[], + next_page_token='def', + ), + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + ], + next_page_token='ghi', + ), + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + user_event.UserEvent(), + ], + ), + RuntimeError, + ) + pages = list(client.list_user_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_user_events_async_pager(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_events), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + user_event.UserEvent(), + user_event.UserEvent(), + ], + next_page_token='abc', + ), + user_event_service.ListUserEventsResponse( + user_events=[], + next_page_token='def', + ), + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + ], + next_page_token='ghi', + ), + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + user_event.UserEvent(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_user_events(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, user_event.UserEvent) + for i in responses) + +@pytest.mark.asyncio +async def test_list_user_events_async_pages(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_events), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + user_event.UserEvent(), + user_event.UserEvent(), + ], + next_page_token='abc', + ), + user_event_service.ListUserEventsResponse( + user_events=[], + next_page_token='def', + ), + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + ], + next_page_token='ghi', + ), + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + user_event.UserEvent(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_user_events(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_purge_user_events(transport: str = 'grpc', request_type=user_event_service.PurgeUserEventsRequest): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.purge_user_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] == user_event_service.PurgeUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_purge_user_events_from_dict(): + test_purge_user_events(request_type=dict) + + +def test_purge_user_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 = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + client.purge_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.PurgeUserEventsRequest() + + +@pytest.mark.asyncio +async def test_purge_user_events_async(transport: str = 'grpc_asyncio', request_type=user_event_service.PurgeUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__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.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.PurgeUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_purge_user_events_async_from_dict(): + await test_purge_user_events_async(request_type=dict) + + +def test_purge_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.PurgeUserEventsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.purge_user_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_purge_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.PurgeUserEventsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.purge_user_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_purge_user_events_flattened(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__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.purge_user_events( + parent='parent_value', + filter='filter_value', + force=True, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].filter == 'filter_value' + assert args[0].force == True + + +def test_purge_user_events_flattened_error(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.purge_user_events( + user_event_service.PurgeUserEventsRequest(), + parent='parent_value', + filter='filter_value', + force=True, + ) + + +@pytest.mark.asyncio +async def test_purge_user_events_flattened_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__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.purge_user_events( + parent='parent_value', + filter='filter_value', + force=True, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].filter == 'filter_value' + assert args[0].force == True + + +@pytest.mark.asyncio +async def test_purge_user_events_flattened_error_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.purge_user_events( + user_event_service.PurgeUserEventsRequest(), + parent='parent_value', + filter='filter_value', + force=True, + ) + + +def test_import_user_events(transport: str = 'grpc', request_type=import_.ImportUserEventsRequest): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_user_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] == import_.ImportUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_user_events_from_dict(): + test_import_user_events(request_type=dict) + + +def test_import_user_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 = UserEventServiceClient( + credentials=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_user_events), + '__call__') as call: + client.import_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_.ImportUserEventsRequest() + + +@pytest.mark.asyncio +async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_.ImportUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_user_events), + '__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_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_.ImportUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_user_events_async_from_dict(): + await test_import_user_events_async(request_type=dict) + + +def test_import_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_.ImportUserEventsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_user_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_import_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_.ImportUserEventsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_user_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_import_user_events_flattened(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__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.import_user_events( + parent='parent_value', + request_id='request_id_value', + input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), + errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].request_id == 'request_id_value' + assert args[0].input_config == import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])) + assert args[0].errors_config == import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value') + + +def test_import_user_events_flattened_error(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.import_user_events( + import_.ImportUserEventsRequest(), + parent='parent_value', + request_id='request_id_value', + input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), + errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), + ) + + +@pytest.mark.asyncio +async def test_import_user_events_flattened_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__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.import_user_events( + parent='parent_value', + request_id='request_id_value', + input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), + errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].request_id == 'request_id_value' + assert args[0].input_config == import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])) + assert args[0].errors_config == import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value') + + +@pytest.mark.asyncio +async def test_import_user_events_flattened_error_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.import_user_events( + import_.ImportUserEventsRequest(), + parent='parent_value', + request_id='request_id_value', + input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), + errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = UserEventServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.UserEventServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.UserEventServiceGrpcTransport, + ) + +def test_user_event_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_user_event_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.recommendationengine_v1beta1.services.user_event_service.transports.UserEventServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'write_user_event', + 'collect_user_event', + 'list_user_events', + 'purge_user_events', + 'import_user_events', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +def test_user_event_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.recommendationengine_v1beta1.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_user_event_service_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.recommendationengine_v1beta1.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + ), + quota_project_id="octopus", + ) + + +def test_user_event_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.recommendationengine_v1beta1.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_user_event_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) + UserEventServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_user_event_service_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + UserEventServiceClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_user_event_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.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_user_event_service_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.UserEventServiceGrpcTransport, grpc_helpers), + (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_user_event_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( + "recommendationengine.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="recommendationengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_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_user_event_service_host_no_port(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='recommendationengine.googleapis.com'), + ) + assert client.transport._host == 'recommendationengine.googleapis.com:443' + + +def test_user_event_service_host_with_port(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='recommendationengine.googleapis.com:8000'), + ) + assert client.transport._host == 'recommendationengine.googleapis.com:8000' + +def test_user_event_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcTransport( + 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_user_event_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcAsyncIOTransport( + 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.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_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.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_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_user_event_service_grpc_lro_client(): + client = UserEventServiceClient( + 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_user_event_service_grpc_lro_async_client(): + client = UserEventServiceAsyncClient( + 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_event_store_path(): + project = "squid" + location = "clam" + catalog = "whelk" + event_store = "octopus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}".format(project=project, location=location, catalog=catalog, event_store=event_store, ) + actual = UserEventServiceClient.event_store_path(project, location, catalog, event_store) + assert expected == actual + + +def test_parse_event_store_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "catalog": "cuttlefish", + "event_store": "mussel", + } + path = UserEventServiceClient.event_store_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_event_store_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = UserEventServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = UserEventServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = UserEventServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = UserEventServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = UserEventServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = UserEventServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = UserEventServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = UserEventServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.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 = UserEventServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = UserEventServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = UserEventServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) From ac6799d138e52e46a6b1c27cc79d9667b817f0bd Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 29 Jun 2021 22:05:00 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/master/packages/owl-bot/README.md --- .../catalog_service/transports/base.py | 2 +- .../catalog_service/transports/grpc.py | 5 +- .../transports/grpc_asyncio.py | 5 +- .../transports/base.py | 2 +- .../transports/grpc.py | 5 +- .../transports/grpc_asyncio.py | 5 +- .../prediction_service/transports/base.py | 2 +- .../prediction_service/transports/grpc.py | 5 +- .../transports/grpc_asyncio.py | 5 +- .../user_event_service/transports/base.py | 2 +- .../user_event_service/transports/grpc.py | 5 +- .../transports/grpc_asyncio.py | 5 +- owl-bot-staging/v1beta1/.coveragerc | 17 - owl-bot-staging/v1beta1/MANIFEST.in | 2 - owl-bot-staging/v1beta1/README.rst | 49 - owl-bot-staging/v1beta1/docs/conf.py | 376 --- owl-bot-staging/v1beta1/docs/index.rst | 7 - .../catalog_service.rst | 10 - .../prediction_api_key_registry.rst | 10 - .../prediction_service.rst | 10 - .../recommendationengine_v1beta1/services.rst | 9 - .../recommendationengine_v1beta1/types.rst | 7 - .../user_event_service.rst | 10 - .../cloud/recommendationengine/__init__.py | 117 - .../cloud/recommendationengine/py.typed | 2 - .../recommendationengine_v1beta1/__init__.py | 118 - .../gapic_metadata.json | 215 -- .../recommendationengine_v1beta1/py.typed | 2 - .../services/__init__.py | 15 - .../services/catalog_service/__init__.py | 22 - .../services/catalog_service/async_client.py | 761 ----- .../services/catalog_service/client.py | 915 ------ .../services/catalog_service/pagers.py | 141 - .../catalog_service/transports/__init__.py | 33 - .../catalog_service/transports/base.py | 290 -- .../catalog_service/transports/grpc.py | 412 --- .../transports/grpc_asyncio.py | 416 --- .../prediction_api_key_registry/__init__.py | 22 - .../async_client.py | 430 --- .../prediction_api_key_registry/client.py | 605 ---- .../prediction_api_key_registry/pagers.py | 140 - .../transports/__init__.py | 33 - .../transports/base.py | 218 -- .../transports/grpc.py | 314 -- .../transports/grpc_asyncio.py | 318 -- .../services/prediction_service/__init__.py | 22 - .../prediction_service/async_client.py | 310 -- .../services/prediction_service/client.py | 490 --- .../services/prediction_service/pagers.py | 140 - .../prediction_service/transports/__init__.py | 33 - .../prediction_service/transports/base.py | 175 -- .../prediction_service/transports/grpc.py | 256 -- .../transports/grpc_asyncio.py | 260 -- .../services/user_event_service/__init__.py | 22 - .../user_event_service/async_client.py | 847 ------ .../services/user_event_service/client.py | 999 ------ .../services/user_event_service/pagers.py | 141 - .../user_event_service/transports/__init__.py | 33 - .../user_event_service/transports/base.py | 269 -- .../user_event_service/transports/grpc.py | 395 --- .../transports/grpc_asyncio.py | 399 --- .../types/__init__.py | 116 - .../types/catalog.py | 312 -- .../types/catalog_service.py | 177 -- .../types/common.py | 91 - .../types/import_.py | 373 --- .../prediction_apikey_registry_service.py | 138 - .../types/prediction_service.py | 271 -- .../types/recommendationengine_resources.py | 25 - .../types/user_event.py | 513 ---- .../types/user_event_service.py | 289 -- owl-bot-staging/v1beta1/mypy.ini | 3 - owl-bot-staging/v1beta1/noxfile.py | 132 - ...p_recommendationengine_v1beta1_keywords.py | 190 -- owl-bot-staging/v1beta1/setup.py | 53 - owl-bot-staging/v1beta1/tests/__init__.py | 16 - .../v1beta1/tests/unit/__init__.py | 16 - .../v1beta1/tests/unit/gapic/__init__.py | 16 - .../recommendationengine_v1beta1/__init__.py | 16 - .../test_catalog_service.py | 2676 ----------------- .../test_prediction_api_key_registry.py | 1840 ------------ .../test_prediction_service.py | 1377 --------- .../test_user_event_service.py | 2394 --------------- .../test_catalog_service.py | 26 +- .../test_prediction_api_key_registry.py | 26 +- .../test_prediction_service.py | 26 +- .../test_user_event_service.py | 26 +- 87 files changed, 124 insertions(+), 21899 deletions(-) delete mode 100644 owl-bot-staging/v1beta1/.coveragerc delete mode 100644 owl-bot-staging/v1beta1/MANIFEST.in delete mode 100644 owl-bot-staging/v1beta1/README.rst delete mode 100644 owl-bot-staging/v1beta1/docs/conf.py delete mode 100644 owl-bot-staging/v1beta1/docs/index.rst delete mode 100644 owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/catalog_service.rst delete mode 100644 owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/prediction_api_key_registry.rst delete mode 100644 owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/prediction_service.rst delete mode 100644 owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/services.rst delete mode 100644 owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/types.rst delete mode 100644 owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/user_event_service.rst delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine/py.typed delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/py.typed delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/async_client.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/client.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/pagers.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/base.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/async_client.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/client.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/pagers.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/base.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/async_client.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/client.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/pagers.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/base.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/async_client.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/client.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/pagers.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/base.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/catalog.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/catalog_service.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/common.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/import_.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/prediction_apikey_registry_service.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/prediction_service.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/recommendationengine_resources.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/user_event.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/user_event_service.py delete mode 100644 owl-bot-staging/v1beta1/mypy.ini delete mode 100644 owl-bot-staging/v1beta1/noxfile.py delete mode 100644 owl-bot-staging/v1beta1/scripts/fixup_recommendationengine_v1beta1_keywords.py delete mode 100644 owl-bot-staging/v1beta1/setup.py delete mode 100644 owl-bot-staging/v1beta1/tests/__init__.py delete mode 100644 owl-bot-staging/v1beta1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/__init__.py delete mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_catalog_service.py delete mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_api_key_registry.py delete mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py delete mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_user_event_service.py diff --git a/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/base.py b/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/base.py index 75c83142..91bb327b 100644 --- a/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/base.py +++ b/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/base.py @@ -103,7 +103,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. diff --git a/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc.py b/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc.py index 3bcb5461..ba82c381 100644 --- a/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc.py +++ b/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc.py @@ -63,6 +63,7 @@ def __init__( client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, ) -> None: """Instantiate the transport. @@ -103,6 +104,8 @@ def __init__( API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -156,7 +159,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc_asyncio.py b/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc_asyncio.py index 3e1a6475..962f0afb 100644 --- a/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc_asyncio.py +++ b/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc_asyncio.py @@ -109,6 +109,7 @@ def __init__( client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id=None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, ) -> None: """Instantiate the transport. @@ -150,6 +151,8 @@ def __init__( API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. Raises: google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport @@ -202,7 +205,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/base.py b/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/base.py index df4019d6..d13921ca 100644 --- a/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/base.py +++ b/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/base.py @@ -101,7 +101,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. diff --git a/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc.py b/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc.py index 1ee36f9b..40e30a79 100644 --- a/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc.py +++ b/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc.py @@ -65,6 +65,7 @@ def __init__( client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, ) -> None: """Instantiate the transport. @@ -105,6 +106,8 @@ def __init__( API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -157,7 +160,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc_asyncio.py b/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc_asyncio.py index 77abd65d..bb568d8d 100644 --- a/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc_asyncio.py +++ b/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc_asyncio.py @@ -111,6 +111,7 @@ def __init__( client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id=None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, ) -> None: """Instantiate the transport. @@ -152,6 +153,8 @@ def __init__( API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. Raises: google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport @@ -203,7 +206,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/base.py b/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/base.py index 80bd529e..1762da2a 100644 --- a/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/base.py +++ b/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/base.py @@ -98,7 +98,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. diff --git a/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc.py b/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc.py index 2dac4441..93ee9231 100644 --- a/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc.py +++ b/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc.py @@ -57,6 +57,7 @@ def __init__( client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, ) -> None: """Instantiate the transport. @@ -97,6 +98,8 @@ def __init__( API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -149,7 +152,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc_asyncio.py b/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc_asyncio.py index 701f1795..95797987 100644 --- a/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc_asyncio.py +++ b/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc_asyncio.py @@ -103,6 +103,7 @@ def __init__( client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id=None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, ) -> None: """Instantiate the transport. @@ -144,6 +145,8 @@ def __init__( API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. Raises: google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport @@ -195,7 +198,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/base.py b/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/base.py index 665dd78a..eea694c2 100644 --- a/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/base.py +++ b/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/base.py @@ -103,7 +103,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. diff --git a/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc.py b/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc.py index 2b439a0a..d4f94a9c 100644 --- a/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc.py +++ b/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc.py @@ -63,6 +63,7 @@ def __init__( client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, ) -> None: """Instantiate the transport. @@ -103,6 +104,8 @@ def __init__( API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -156,7 +159,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc_asyncio.py b/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc_asyncio.py index 3ded95a3..720bd026 100644 --- a/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc_asyncio.py +++ b/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc_asyncio.py @@ -109,6 +109,7 @@ def __init__( client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id=None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, ) -> None: """Instantiate the transport. @@ -150,6 +151,8 @@ def __init__( API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. Raises: google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport @@ -202,7 +205,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/owl-bot-staging/v1beta1/.coveragerc b/owl-bot-staging/v1beta1/.coveragerc deleted file mode 100644 index 41724c80..00000000 --- a/owl-bot-staging/v1beta1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/recommendationengine/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1beta1/MANIFEST.in b/owl-bot-staging/v1beta1/MANIFEST.in deleted file mode 100644 index 5054f413..00000000 --- a/owl-bot-staging/v1beta1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/recommendationengine *.py -recursive-include google/cloud/recommendationengine_v1beta1 *.py diff --git a/owl-bot-staging/v1beta1/README.rst b/owl-bot-staging/v1beta1/README.rst deleted file mode 100644 index 11130784..00000000 --- a/owl-bot-staging/v1beta1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Recommendationengine 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 Recommendationengine 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/v1beta1/docs/conf.py b/owl-bot-staging/v1beta1/docs/conf.py deleted file mode 100644 index 1bbaeeeb..00000000 --- a/owl-bot-staging/v1beta1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-recommendations-ai documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "1.6.3" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-cloud-recommendations-ai" -copyright = u"2020, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google 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-recommendations-ai-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - master_doc, - "google-cloud-recommendations-ai.tex", - u"google-cloud-recommendations-ai Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - master_doc, - "google-cloud-recommendations-ai", - u"Google Cloud Recommendationengine Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - master_doc, - "google-cloud-recommendations-ai", - u"google-cloud-recommendations-ai Documentation", - author, - "google-cloud-recommendations-ai", - "GAPIC library for Google Cloud Recommendationengine 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/v1beta1/docs/index.rst b/owl-bot-staging/v1beta1/docs/index.rst deleted file mode 100644 index b7e1db6b..00000000 --- a/owl-bot-staging/v1beta1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - recommendationengine_v1beta1/services - recommendationengine_v1beta1/types diff --git a/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/catalog_service.rst b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/catalog_service.rst deleted file mode 100644 index 48f7c814..00000000 --- a/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/catalog_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -CatalogService --------------------------------- - -.. automodule:: google.cloud.recommendationengine_v1beta1.services.catalog_service - :members: - :inherited-members: - -.. automodule:: google.cloud.recommendationengine_v1beta1.services.catalog_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/prediction_api_key_registry.rst b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/prediction_api_key_registry.rst deleted file mode 100644 index 74874c31..00000000 --- a/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/prediction_api_key_registry.rst +++ /dev/null @@ -1,10 +0,0 @@ -PredictionApiKeyRegistry ------------------------------------------- - -.. automodule:: google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry - :members: - :inherited-members: - -.. automodule:: google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/prediction_service.rst b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/prediction_service.rst deleted file mode 100644 index 7d2fc56d..00000000 --- a/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/prediction_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -PredictionService ------------------------------------ - -.. automodule:: google.cloud.recommendationengine_v1beta1.services.prediction_service - :members: - :inherited-members: - -.. automodule:: google.cloud.recommendationengine_v1beta1.services.prediction_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/services.rst b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/services.rst deleted file mode 100644 index ced8732d..00000000 --- a/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/services.rst +++ /dev/null @@ -1,9 +0,0 @@ -Services for Google Cloud Recommendationengine v1beta1 API -========================================================== -.. toctree:: - :maxdepth: 2 - - catalog_service - prediction_api_key_registry - prediction_service - user_event_service diff --git a/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/types.rst b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/types.rst deleted file mode 100644 index 679552ed..00000000 --- a/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Recommendationengine v1beta1 API -======================================================= - -.. automodule:: google.cloud.recommendationengine_v1beta1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/user_event_service.rst b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/user_event_service.rst deleted file mode 100644 index 728ec7e9..00000000 --- a/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/user_event_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -UserEventService ----------------------------------- - -.. automodule:: google.cloud.recommendationengine_v1beta1.services.user_event_service - :members: - :inherited-members: - -.. automodule:: google.cloud.recommendationengine_v1beta1.services.user_event_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine/__init__.py deleted file mode 100644 index 61922786..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine/__init__.py +++ /dev/null @@ -1,117 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.cloud.recommendationengine_v1beta1.services.catalog_service.client import CatalogServiceClient -from google.cloud.recommendationengine_v1beta1.services.catalog_service.async_client import CatalogServiceAsyncClient -from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry.client import PredictionApiKeyRegistryClient -from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry.async_client import PredictionApiKeyRegistryAsyncClient -from google.cloud.recommendationengine_v1beta1.services.prediction_service.client import PredictionServiceClient -from google.cloud.recommendationengine_v1beta1.services.prediction_service.async_client import PredictionServiceAsyncClient -from google.cloud.recommendationengine_v1beta1.services.user_event_service.client import UserEventServiceClient -from google.cloud.recommendationengine_v1beta1.services.user_event_service.async_client import UserEventServiceAsyncClient - -from google.cloud.recommendationengine_v1beta1.types.catalog import CatalogItem -from google.cloud.recommendationengine_v1beta1.types.catalog import Image -from google.cloud.recommendationengine_v1beta1.types.catalog import ProductCatalogItem -from google.cloud.recommendationengine_v1beta1.types.catalog_service import CreateCatalogItemRequest -from google.cloud.recommendationengine_v1beta1.types.catalog_service import DeleteCatalogItemRequest -from google.cloud.recommendationengine_v1beta1.types.catalog_service import GetCatalogItemRequest -from google.cloud.recommendationengine_v1beta1.types.catalog_service import ListCatalogItemsRequest -from google.cloud.recommendationengine_v1beta1.types.catalog_service import ListCatalogItemsResponse -from google.cloud.recommendationengine_v1beta1.types.catalog_service import UpdateCatalogItemRequest -from google.cloud.recommendationengine_v1beta1.types.common import FeatureMap -from google.cloud.recommendationengine_v1beta1.types.import_ import CatalogInlineSource -from google.cloud.recommendationengine_v1beta1.types.import_ import GcsSource -from google.cloud.recommendationengine_v1beta1.types.import_ import ImportCatalogItemsRequest -from google.cloud.recommendationengine_v1beta1.types.import_ import ImportCatalogItemsResponse -from google.cloud.recommendationengine_v1beta1.types.import_ import ImportErrorsConfig -from google.cloud.recommendationengine_v1beta1.types.import_ import ImportMetadata -from google.cloud.recommendationengine_v1beta1.types.import_ import ImportUserEventsRequest -from google.cloud.recommendationengine_v1beta1.types.import_ import ImportUserEventsResponse -from google.cloud.recommendationengine_v1beta1.types.import_ import InputConfig -from google.cloud.recommendationengine_v1beta1.types.import_ import UserEventImportSummary -from google.cloud.recommendationengine_v1beta1.types.import_ import UserEventInlineSource -from google.cloud.recommendationengine_v1beta1.types.prediction_apikey_registry_service import CreatePredictionApiKeyRegistrationRequest -from google.cloud.recommendationengine_v1beta1.types.prediction_apikey_registry_service import DeletePredictionApiKeyRegistrationRequest -from google.cloud.recommendationengine_v1beta1.types.prediction_apikey_registry_service import ListPredictionApiKeyRegistrationsRequest -from google.cloud.recommendationengine_v1beta1.types.prediction_apikey_registry_service import ListPredictionApiKeyRegistrationsResponse -from google.cloud.recommendationengine_v1beta1.types.prediction_apikey_registry_service import PredictionApiKeyRegistration -from google.cloud.recommendationengine_v1beta1.types.prediction_service import PredictRequest -from google.cloud.recommendationengine_v1beta1.types.prediction_service import PredictResponse -from google.cloud.recommendationengine_v1beta1.types.user_event import EventDetail -from google.cloud.recommendationengine_v1beta1.types.user_event import ProductDetail -from google.cloud.recommendationengine_v1beta1.types.user_event import ProductEventDetail -from google.cloud.recommendationengine_v1beta1.types.user_event import PurchaseTransaction -from google.cloud.recommendationengine_v1beta1.types.user_event import UserEvent -from google.cloud.recommendationengine_v1beta1.types.user_event import UserInfo -from google.cloud.recommendationengine_v1beta1.types.user_event_service import CollectUserEventRequest -from google.cloud.recommendationengine_v1beta1.types.user_event_service import ListUserEventsRequest -from google.cloud.recommendationengine_v1beta1.types.user_event_service import ListUserEventsResponse -from google.cloud.recommendationengine_v1beta1.types.user_event_service import PurgeUserEventsMetadata -from google.cloud.recommendationengine_v1beta1.types.user_event_service import PurgeUserEventsRequest -from google.cloud.recommendationengine_v1beta1.types.user_event_service import PurgeUserEventsResponse -from google.cloud.recommendationengine_v1beta1.types.user_event_service import WriteUserEventRequest - -__all__ = ('CatalogServiceClient', - 'CatalogServiceAsyncClient', - 'PredictionApiKeyRegistryClient', - 'PredictionApiKeyRegistryAsyncClient', - 'PredictionServiceClient', - 'PredictionServiceAsyncClient', - 'UserEventServiceClient', - 'UserEventServiceAsyncClient', - 'CatalogItem', - 'Image', - 'ProductCatalogItem', - 'CreateCatalogItemRequest', - 'DeleteCatalogItemRequest', - 'GetCatalogItemRequest', - 'ListCatalogItemsRequest', - 'ListCatalogItemsResponse', - 'UpdateCatalogItemRequest', - 'FeatureMap', - 'CatalogInlineSource', - 'GcsSource', - 'ImportCatalogItemsRequest', - 'ImportCatalogItemsResponse', - 'ImportErrorsConfig', - 'ImportMetadata', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'InputConfig', - 'UserEventImportSummary', - 'UserEventInlineSource', - 'CreatePredictionApiKeyRegistrationRequest', - 'DeletePredictionApiKeyRegistrationRequest', - 'ListPredictionApiKeyRegistrationsRequest', - 'ListPredictionApiKeyRegistrationsResponse', - 'PredictionApiKeyRegistration', - 'PredictRequest', - 'PredictResponse', - 'EventDetail', - 'ProductDetail', - 'ProductEventDetail', - 'PurchaseTransaction', - 'UserEvent', - 'UserInfo', - 'CollectUserEventRequest', - 'ListUserEventsRequest', - 'ListUserEventsResponse', - 'PurgeUserEventsMetadata', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - 'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine/py.typed b/owl-bot-staging/v1beta1/google/cloud/recommendationengine/py.typed deleted file mode 100644 index 41689a36..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-recommendations-ai package uses inline types. diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/__init__.py deleted file mode 100644 index 532c2908..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/__init__.py +++ /dev/null @@ -1,118 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .services.catalog_service import CatalogServiceClient -from .services.catalog_service import CatalogServiceAsyncClient -from .services.prediction_api_key_registry import PredictionApiKeyRegistryClient -from .services.prediction_api_key_registry import PredictionApiKeyRegistryAsyncClient -from .services.prediction_service import PredictionServiceClient -from .services.prediction_service import PredictionServiceAsyncClient -from .services.user_event_service import UserEventServiceClient -from .services.user_event_service import UserEventServiceAsyncClient - -from .types.catalog import CatalogItem -from .types.catalog import Image -from .types.catalog import ProductCatalogItem -from .types.catalog_service import CreateCatalogItemRequest -from .types.catalog_service import DeleteCatalogItemRequest -from .types.catalog_service import GetCatalogItemRequest -from .types.catalog_service import ListCatalogItemsRequest -from .types.catalog_service import ListCatalogItemsResponse -from .types.catalog_service import UpdateCatalogItemRequest -from .types.common import FeatureMap -from .types.import_ import CatalogInlineSource -from .types.import_ import GcsSource -from .types.import_ import ImportCatalogItemsRequest -from .types.import_ import ImportCatalogItemsResponse -from .types.import_ import ImportErrorsConfig -from .types.import_ import ImportMetadata -from .types.import_ import ImportUserEventsRequest -from .types.import_ import ImportUserEventsResponse -from .types.import_ import InputConfig -from .types.import_ import UserEventImportSummary -from .types.import_ import UserEventInlineSource -from .types.prediction_apikey_registry_service import CreatePredictionApiKeyRegistrationRequest -from .types.prediction_apikey_registry_service import DeletePredictionApiKeyRegistrationRequest -from .types.prediction_apikey_registry_service import ListPredictionApiKeyRegistrationsRequest -from .types.prediction_apikey_registry_service import ListPredictionApiKeyRegistrationsResponse -from .types.prediction_apikey_registry_service import PredictionApiKeyRegistration -from .types.prediction_service import PredictRequest -from .types.prediction_service import PredictResponse -from .types.user_event import EventDetail -from .types.user_event import ProductDetail -from .types.user_event import ProductEventDetail -from .types.user_event import PurchaseTransaction -from .types.user_event import UserEvent -from .types.user_event import UserInfo -from .types.user_event_service import CollectUserEventRequest -from .types.user_event_service import ListUserEventsRequest -from .types.user_event_service import ListUserEventsResponse -from .types.user_event_service import PurgeUserEventsMetadata -from .types.user_event_service import PurgeUserEventsRequest -from .types.user_event_service import PurgeUserEventsResponse -from .types.user_event_service import WriteUserEventRequest - -__all__ = ( - 'CatalogServiceAsyncClient', - 'PredictionApiKeyRegistryAsyncClient', - 'PredictionServiceAsyncClient', - 'UserEventServiceAsyncClient', -'CatalogInlineSource', -'CatalogItem', -'CatalogServiceClient', -'CollectUserEventRequest', -'CreateCatalogItemRequest', -'CreatePredictionApiKeyRegistrationRequest', -'DeleteCatalogItemRequest', -'DeletePredictionApiKeyRegistrationRequest', -'EventDetail', -'FeatureMap', -'GcsSource', -'GetCatalogItemRequest', -'Image', -'ImportCatalogItemsRequest', -'ImportCatalogItemsResponse', -'ImportErrorsConfig', -'ImportMetadata', -'ImportUserEventsRequest', -'ImportUserEventsResponse', -'InputConfig', -'ListCatalogItemsRequest', -'ListCatalogItemsResponse', -'ListPredictionApiKeyRegistrationsRequest', -'ListPredictionApiKeyRegistrationsResponse', -'ListUserEventsRequest', -'ListUserEventsResponse', -'PredictRequest', -'PredictResponse', -'PredictionApiKeyRegistration', -'PredictionApiKeyRegistryClient', -'PredictionServiceClient', -'ProductCatalogItem', -'ProductDetail', -'ProductEventDetail', -'PurchaseTransaction', -'PurgeUserEventsMetadata', -'PurgeUserEventsRequest', -'PurgeUserEventsResponse', -'UpdateCatalogItemRequest', -'UserEvent', -'UserEventImportSummary', -'UserEventInlineSource', -'UserEventServiceClient', -'UserInfo', -'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/gapic_metadata.json b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/gapic_metadata.json deleted file mode 100644 index b5ae877c..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/gapic_metadata.json +++ /dev/null @@ -1,215 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.recommendationengine_v1beta1", - "protoPackage": "google.cloud.recommendationengine.v1beta1", - "schema": "1.0", - "services": { - "CatalogService": { - "clients": { - "grpc": { - "libraryClient": "CatalogServiceClient", - "rpcs": { - "CreateCatalogItem": { - "methods": [ - "create_catalog_item" - ] - }, - "DeleteCatalogItem": { - "methods": [ - "delete_catalog_item" - ] - }, - "GetCatalogItem": { - "methods": [ - "get_catalog_item" - ] - }, - "ImportCatalogItems": { - "methods": [ - "import_catalog_items" - ] - }, - "ListCatalogItems": { - "methods": [ - "list_catalog_items" - ] - }, - "UpdateCatalogItem": { - "methods": [ - "update_catalog_item" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CatalogServiceAsyncClient", - "rpcs": { - "CreateCatalogItem": { - "methods": [ - "create_catalog_item" - ] - }, - "DeleteCatalogItem": { - "methods": [ - "delete_catalog_item" - ] - }, - "GetCatalogItem": { - "methods": [ - "get_catalog_item" - ] - }, - "ImportCatalogItems": { - "methods": [ - "import_catalog_items" - ] - }, - "ListCatalogItems": { - "methods": [ - "list_catalog_items" - ] - }, - "UpdateCatalogItem": { - "methods": [ - "update_catalog_item" - ] - } - } - } - } - }, - "PredictionApiKeyRegistry": { - "clients": { - "grpc": { - "libraryClient": "PredictionApiKeyRegistryClient", - "rpcs": { - "CreatePredictionApiKeyRegistration": { - "methods": [ - "create_prediction_api_key_registration" - ] - }, - "DeletePredictionApiKeyRegistration": { - "methods": [ - "delete_prediction_api_key_registration" - ] - }, - "ListPredictionApiKeyRegistrations": { - "methods": [ - "list_prediction_api_key_registrations" - ] - } - } - }, - "grpc-async": { - "libraryClient": "PredictionApiKeyRegistryAsyncClient", - "rpcs": { - "CreatePredictionApiKeyRegistration": { - "methods": [ - "create_prediction_api_key_registration" - ] - }, - "DeletePredictionApiKeyRegistration": { - "methods": [ - "delete_prediction_api_key_registration" - ] - }, - "ListPredictionApiKeyRegistrations": { - "methods": [ - "list_prediction_api_key_registrations" - ] - } - } - } - } - }, - "PredictionService": { - "clients": { - "grpc": { - "libraryClient": "PredictionServiceClient", - "rpcs": { - "Predict": { - "methods": [ - "predict" - ] - } - } - }, - "grpc-async": { - "libraryClient": "PredictionServiceAsyncClient", - "rpcs": { - "Predict": { - "methods": [ - "predict" - ] - } - } - } - } - }, - "UserEventService": { - "clients": { - "grpc": { - "libraryClient": "UserEventServiceClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "ListUserEvents": { - "methods": [ - "list_user_events" - ] - }, - "PurgeUserEvents": { - "methods": [ - "purge_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - }, - "grpc-async": { - "libraryClient": "UserEventServiceAsyncClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "ListUserEvents": { - "methods": [ - "list_user_events" - ] - }, - "PurgeUserEvents": { - "methods": [ - "purge_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/py.typed b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/py.typed deleted file mode 100644 index 41689a36..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-recommendations-ai package uses inline types. diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/__init__.py deleted file mode 100644 index 4de65971..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/__init__.py deleted file mode 100644 index 316640d9..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import CatalogServiceClient -from .async_client import CatalogServiceAsyncClient - -__all__ = ( - 'CatalogServiceClient', - 'CatalogServiceAsyncClient', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/async_client.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/async_client.py deleted file mode 100644 index 605dafc2..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/async_client.py +++ /dev/null @@ -1,761 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.recommendationengine_v1beta1.services.catalog_service import pagers -from google.cloud.recommendationengine_v1beta1.types import catalog -from google.cloud.recommendationengine_v1beta1.types import catalog_service -from google.cloud.recommendationengine_v1beta1.types import common -from google.cloud.recommendationengine_v1beta1.types import import_ -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport -from .client import CatalogServiceClient - - -class CatalogServiceAsyncClient: - """Service for ingesting catalog information of the customer's - website. - """ - - _client: CatalogServiceClient - - DEFAULT_ENDPOINT = CatalogServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CatalogServiceClient.DEFAULT_MTLS_ENDPOINT - - catalog_path = staticmethod(CatalogServiceClient.catalog_path) - parse_catalog_path = staticmethod(CatalogServiceClient.parse_catalog_path) - catalog_item_path_path = staticmethod(CatalogServiceClient.catalog_item_path_path) - parse_catalog_item_path_path = staticmethod(CatalogServiceClient.parse_catalog_item_path_path) - common_billing_account_path = staticmethod(CatalogServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CatalogServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CatalogServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CatalogServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CatalogServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CatalogServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CatalogServiceClient.common_project_path) - parse_common_project_path = staticmethod(CatalogServiceClient.parse_common_project_path) - common_location_path = staticmethod(CatalogServiceClient.common_location_path) - parse_common_location_path = staticmethod(CatalogServiceClient.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: - CatalogServiceAsyncClient: The constructed client. - """ - return CatalogServiceClient.from_service_account_info.__func__(CatalogServiceAsyncClient, 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: - CatalogServiceAsyncClient: The constructed client. - """ - return CatalogServiceClient.from_service_account_file.__func__(CatalogServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> CatalogServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CatalogServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(CatalogServiceClient).get_transport_class, type(CatalogServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, CatalogServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the catalog service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.CatalogServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = CatalogServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_catalog_item(self, - request: catalog_service.CreateCatalogItemRequest = None, - *, - parent: str = None, - catalog_item: catalog.CatalogItem = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CatalogItem: - r"""Creates a catalog item. - - Args: - request (:class:`google.cloud.recommendationengine_v1beta1.types.CreateCatalogItemRequest`): - The request object. Request message for - CreateCatalogItem method. - parent (:class:`str`): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - catalog_item (:class:`google.cloud.recommendationengine_v1beta1.types.CatalogItem`): - Required. The catalog item to create. - This corresponds to the ``catalog_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.recommendationengine_v1beta1.types.CatalogItem: - CatalogItem captures all metadata - information of items to be recommended. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, catalog_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.") - - request = catalog_service.CreateCatalogItemRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if catalog_item is not None: - request.catalog_item = catalog_item - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_catalog_item, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_catalog_item(self, - request: catalog_service.GetCatalogItemRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CatalogItem: - r"""Gets a specific catalog item. - - Args: - request (:class:`google.cloud.recommendationengine_v1beta1.types.GetCatalogItemRequest`): - The request object. Request message for GetCatalogItem - method. - name (:class:`str`): - Required. Full resource name of catalog item, such as - ``projects/*/locations/global/catalogs/default_catalog/catalogitems/some_catalog_item_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.recommendationengine_v1beta1.types.CatalogItem: - CatalogItem captures all metadata - information of items to be recommended. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.GetCatalogItemRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_catalog_item, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_catalog_items(self, - request: catalog_service.ListCatalogItemsRequest = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCatalogItemsAsyncPager: - r"""Gets a list of catalog items. - - Args: - request (:class:`google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsRequest`): - The request object. Request message for ListCatalogItems - method. - parent (:class:`str`): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - Optional. A filter to apply on the - list results. - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.recommendationengine_v1beta1.services.catalog_service.pagers.ListCatalogItemsAsyncPager: - Response message for ListCatalogItems - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, filter]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.ListCatalogItemsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_catalog_items, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListCatalogItemsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_catalog_item(self, - request: catalog_service.UpdateCatalogItemRequest = None, - *, - name: str = None, - catalog_item: catalog.CatalogItem = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CatalogItem: - r"""Updates a catalog item. Partial updating is - supported. Non-existing items will be created. - - Args: - request (:class:`google.cloud.recommendationengine_v1beta1.types.UpdateCatalogItemRequest`): - The request object. Request message for - UpdateCatalogItem method. - name (:class:`str`): - Required. Full resource name of catalog item, such as - "projects/*/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_id". - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - catalog_item (:class:`google.cloud.recommendationengine_v1beta1.types.CatalogItem`): - Required. The catalog item to update/create. The - 'catalog_item_id' field has to match that in the 'name'. - - This corresponds to the ``catalog_item`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. Indicates which fields in - the provided 'item' to update. If not - set, will by default update all fields. - - 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.recommendationengine_v1beta1.types.CatalogItem: - CatalogItem captures all metadata - information of items to be recommended. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, catalog_item, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.UpdateCatalogItemRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if catalog_item is not None: - request.catalog_item = catalog_item - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_catalog_item, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_catalog_item(self, - request: catalog_service.DeleteCatalogItemRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a catalog item. - - Args: - request (:class:`google.cloud.recommendationengine_v1beta1.types.DeleteCatalogItemRequest`): - The request object. Request message for - DeleteCatalogItem method. - name (:class:`str`): - Required. Full resource name of catalog item, such as - ``projects/*/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_id``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = catalog_service.DeleteCatalogItemRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_catalog_item, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def import_catalog_items(self, - request: import_.ImportCatalogItemsRequest = None, - *, - parent: str = None, - request_id: str = None, - input_config: import_.InputConfig = None, - errors_config: import_.ImportErrorsConfig = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of multiple catalog items. Request - processing may be synchronous. No partial updating - supported. Non-existing items will be created. - - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully updated. - - Args: - request (:class:`google.cloud.recommendationengine_v1beta1.types.ImportCatalogItemsRequest`): - The request object. Request message for Import methods. - parent (:class:`str`): - Required. - ``projects/1234/locations/global/catalogs/default_catalog`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - request_id (:class:`str`): - Optional. Unique identifier provided - by client, within the ancestor dataset - scope. Ensures idempotency and used for - request deduplication. Server-generated - if unspecified. Up to 128 characters - long. This is returned as - google.longrunning.Operation.name in the - response. - - This corresponds to the ``request_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - input_config (:class:`google.cloud.recommendationengine_v1beta1.types.InputConfig`): - Required. The desired input location - of the data. - - This corresponds to the ``input_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - errors_config (:class:`google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig`): - Optional. The desired location of - errors incurred during the Import. - - This corresponds to the ``errors_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.recommendationengine_v1beta1.types.ImportCatalogItemsResponse` Response of the ImportCatalogItemsRequest. If the long running - operation is done, then this message is returned by - the google.longrunning.Operations.response field if - the operation was successful. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, request_id, input_config, errors_config]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = import_.ImportCatalogItemsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if request_id is not None: - request.request_id = request_id - if input_config is not None: - request.input_config = input_config - if errors_config is not None: - request.errors_config = errors_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_catalog_items, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_.ImportCatalogItemsResponse, - metadata_type=import_.ImportMetadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-recommendations-ai", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CatalogServiceAsyncClient", -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/client.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/client.py deleted file mode 100644 index d5cf1535..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/client.py +++ /dev/null @@ -1,915 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.recommendationengine_v1beta1.services.catalog_service import pagers -from google.cloud.recommendationengine_v1beta1.types import catalog -from google.cloud.recommendationengine_v1beta1.types import catalog_service -from google.cloud.recommendationengine_v1beta1.types import common -from google.cloud.recommendationengine_v1beta1.types import import_ -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CatalogServiceGrpcTransport -from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport - - -class CatalogServiceClientMeta(type): - """Metaclass for the CatalogService 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[CatalogServiceTransport]] - _transport_registry["grpc"] = CatalogServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CatalogServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[CatalogServiceTransport]: - """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 CatalogServiceClient(metaclass=CatalogServiceClientMeta): - """Service for ingesting catalog information of the customer's - website. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "recommendationengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CatalogServiceClient: 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: - CatalogServiceClient: 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) -> CatalogServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CatalogServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def catalog_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_path(path: str) -> Dict[str,str]: - """Parses a catalog path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def catalog_item_path_path(project: str,location: str,catalog: str,) -> str: - """Returns a fully-qualified catalog_item_path string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/catalogItems/{catalog_item_path=**}".format(project=project, location=location, catalog=catalog, ) - - @staticmethod - def parse_catalog_item_path_path(path: str) -> Dict[str,str]: - """Parses a catalog_item_path path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/catalogItems/{catalog_item_path=**}$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, CatalogServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the catalog service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, CatalogServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, CatalogServiceTransport): - # transport is a CatalogServiceTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def create_catalog_item(self, - request: catalog_service.CreateCatalogItemRequest = None, - *, - parent: str = None, - catalog_item: catalog.CatalogItem = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CatalogItem: - r"""Creates a catalog item. - - Args: - request (google.cloud.recommendationengine_v1beta1.types.CreateCatalogItemRequest): - The request object. Request message for - CreateCatalogItem method. - parent (str): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - catalog_item (google.cloud.recommendationengine_v1beta1.types.CatalogItem): - Required. The catalog item to create. - This corresponds to the ``catalog_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.recommendationengine_v1beta1.types.CatalogItem: - CatalogItem captures all metadata - information of items to be recommended. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, catalog_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.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.CreateCatalogItemRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.CreateCatalogItemRequest): - request = catalog_service.CreateCatalogItemRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if catalog_item is not None: - request.catalog_item = catalog_item - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_catalog_item] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_catalog_item(self, - request: catalog_service.GetCatalogItemRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CatalogItem: - r"""Gets a specific catalog item. - - Args: - request (google.cloud.recommendationengine_v1beta1.types.GetCatalogItemRequest): - The request object. Request message for GetCatalogItem - method. - name (str): - Required. Full resource name of catalog item, such as - ``projects/*/locations/global/catalogs/default_catalog/catalogitems/some_catalog_item_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.recommendationengine_v1beta1.types.CatalogItem: - CatalogItem captures all metadata - information of items to be recommended. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.GetCatalogItemRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.GetCatalogItemRequest): - request = catalog_service.GetCatalogItemRequest(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_catalog_item] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_catalog_items(self, - request: catalog_service.ListCatalogItemsRequest = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCatalogItemsPager: - r"""Gets a list of catalog items. - - Args: - request (google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsRequest): - The request object. Request message for ListCatalogItems - method. - parent (str): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - Optional. A filter to apply on the - list results. - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.recommendationengine_v1beta1.services.catalog_service.pagers.ListCatalogItemsPager: - Response message for ListCatalogItems - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, filter]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.ListCatalogItemsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.ListCatalogItemsRequest): - request = catalog_service.ListCatalogItemsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_catalog_items] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListCatalogItemsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_catalog_item(self, - request: catalog_service.UpdateCatalogItemRequest = None, - *, - name: str = None, - catalog_item: catalog.CatalogItem = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> catalog.CatalogItem: - r"""Updates a catalog item. Partial updating is - supported. Non-existing items will be created. - - Args: - request (google.cloud.recommendationengine_v1beta1.types.UpdateCatalogItemRequest): - The request object. Request message for - UpdateCatalogItem method. - name (str): - Required. Full resource name of catalog item, such as - "projects/*/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_id". - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - catalog_item (google.cloud.recommendationengine_v1beta1.types.CatalogItem): - Required. The catalog item to update/create. The - 'catalog_item_id' field has to match that in the 'name'. - - This corresponds to the ``catalog_item`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Indicates which fields in - the provided 'item' to update. If not - set, will by default update all fields. - - 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.recommendationengine_v1beta1.types.CatalogItem: - CatalogItem captures all metadata - information of items to be recommended. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, catalog_item, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.UpdateCatalogItemRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.UpdateCatalogItemRequest): - request = catalog_service.UpdateCatalogItemRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if catalog_item is not None: - request.catalog_item = catalog_item - 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_catalog_item] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_catalog_item(self, - request: catalog_service.DeleteCatalogItemRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a catalog item. - - Args: - request (google.cloud.recommendationengine_v1beta1.types.DeleteCatalogItemRequest): - The request object. Request message for - DeleteCatalogItem method. - name (str): - Required. Full resource name of catalog item, such as - ``projects/*/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_id``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a catalog_service.DeleteCatalogItemRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, catalog_service.DeleteCatalogItemRequest): - request = catalog_service.DeleteCatalogItemRequest(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_catalog_item] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def import_catalog_items(self, - request: import_.ImportCatalogItemsRequest = None, - *, - parent: str = None, - request_id: str = None, - input_config: import_.InputConfig = None, - errors_config: import_.ImportErrorsConfig = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of multiple catalog items. Request - processing may be synchronous. No partial updating - supported. Non-existing items will be created. - - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully updated. - - Args: - request (google.cloud.recommendationengine_v1beta1.types.ImportCatalogItemsRequest): - The request object. Request message for Import methods. - parent (str): - Required. - ``projects/1234/locations/global/catalogs/default_catalog`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - request_id (str): - Optional. Unique identifier provided - by client, within the ancestor dataset - scope. Ensures idempotency and used for - request deduplication. Server-generated - if unspecified. Up to 128 characters - long. This is returned as - google.longrunning.Operation.name in the - response. - - This corresponds to the ``request_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - input_config (google.cloud.recommendationengine_v1beta1.types.InputConfig): - Required. The desired input location - of the data. - - This corresponds to the ``input_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - errors_config (google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig): - Optional. The desired location of - errors incurred during the Import. - - This corresponds to the ``errors_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.recommendationengine_v1beta1.types.ImportCatalogItemsResponse` Response of the ImportCatalogItemsRequest. If the long running - operation is done, then this message is returned by - the google.longrunning.Operations.response field if - the operation was successful. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, request_id, input_config, errors_config]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a import_.ImportCatalogItemsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_.ImportCatalogItemsRequest): - request = import_.ImportCatalogItemsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if request_id is not None: - request.request_id = request_id - if input_config is not None: - request.input_config = input_config - if errors_config is not None: - request.errors_config = errors_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_catalog_items] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_.ImportCatalogItemsResponse, - metadata_type=import_.ImportMetadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-recommendations-ai", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "CatalogServiceClient", -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/pagers.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/pagers.py deleted file mode 100644 index 63720f3c..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/pagers.py +++ /dev/null @@ -1,141 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.recommendationengine_v1beta1.types import catalog -from google.cloud.recommendationengine_v1beta1.types import catalog_service - - -class ListCatalogItemsPager: - """A pager for iterating through ``list_catalog_items`` requests. - - This class thinly wraps an initial - :class:`google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``catalog_items`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListCatalogItems`` requests and continue to iterate - through the ``catalog_items`` field on the - corresponding responses. - - All the usual :class:`google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsResponse` - 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[..., catalog_service.ListCatalogItemsResponse], - request: catalog_service.ListCatalogItemsRequest, - response: catalog_service.ListCatalogItemsResponse, - *, - 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.recommendationengine_v1beta1.types.ListCatalogItemsRequest): - The initial request object. - response (google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsResponse): - 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 = catalog_service.ListCatalogItemsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[catalog_service.ListCatalogItemsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[catalog.CatalogItem]: - for page in self.pages: - yield from page.catalog_items - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCatalogItemsAsyncPager: - """A pager for iterating through ``list_catalog_items`` requests. - - This class thinly wraps an initial - :class:`google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``catalog_items`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListCatalogItems`` requests and continue to iterate - through the ``catalog_items`` field on the - corresponding responses. - - All the usual :class:`google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsResponse` - 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[catalog_service.ListCatalogItemsResponse]], - request: catalog_service.ListCatalogItemsRequest, - response: catalog_service.ListCatalogItemsResponse, - *, - 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.recommendationengine_v1beta1.types.ListCatalogItemsRequest): - The initial request object. - response (google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsResponse): - 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 = catalog_service.ListCatalogItemsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[catalog_service.ListCatalogItemsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[catalog.CatalogItem]: - async def async_generator(): - async for page in self.pages: - for response in page.catalog_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/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/__init__.py deleted file mode 100644 index 7d55f7e9..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import CatalogServiceTransport -from .grpc import CatalogServiceGrpcTransport -from .grpc_asyncio import CatalogServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CatalogServiceTransport]] -_transport_registry['grpc'] = CatalogServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CatalogServiceGrpcAsyncIOTransport - -__all__ = ( - 'CatalogServiceTransport', - 'CatalogServiceGrpcTransport', - 'CatalogServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/base.py deleted file mode 100644 index f1d829ed..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/base.py +++ /dev/null @@ -1,290 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.recommendationengine_v1beta1.types import catalog -from google.cloud.recommendationengine_v1beta1.types import catalog_service -from google.cloud.recommendationengine_v1beta1.types import import_ -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-recommendations-ai', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class CatalogServiceTransport(abc.ABC): - """Abstract transport class for CatalogService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'recommendationengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials is service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_catalog_item: gapic_v1.method.wrap_method( - self.create_catalog_item, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.get_catalog_item: gapic_v1.method.wrap_method( - self.get_catalog_item, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_catalog_items: gapic_v1.method.wrap_method( - self.list_catalog_items, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.update_catalog_item: gapic_v1.method.wrap_method( - self.update_catalog_item, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.delete_catalog_item: gapic_v1.method.wrap_method( - self.delete_catalog_item, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.import_catalog_items: gapic_v1.method.wrap_method( - self.import_catalog_items, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_catalog_item(self) -> Callable[ - [catalog_service.CreateCatalogItemRequest], - Union[ - catalog.CatalogItem, - Awaitable[catalog.CatalogItem] - ]]: - raise NotImplementedError() - - @property - def get_catalog_item(self) -> Callable[ - [catalog_service.GetCatalogItemRequest], - Union[ - catalog.CatalogItem, - Awaitable[catalog.CatalogItem] - ]]: - raise NotImplementedError() - - @property - def list_catalog_items(self) -> Callable[ - [catalog_service.ListCatalogItemsRequest], - Union[ - catalog_service.ListCatalogItemsResponse, - Awaitable[catalog_service.ListCatalogItemsResponse] - ]]: - raise NotImplementedError() - - @property - def update_catalog_item(self) -> Callable[ - [catalog_service.UpdateCatalogItemRequest], - Union[ - catalog.CatalogItem, - Awaitable[catalog.CatalogItem] - ]]: - raise NotImplementedError() - - @property - def delete_catalog_item(self) -> Callable[ - [catalog_service.DeleteCatalogItemRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def import_catalog_items(self) -> Callable[ - [import_.ImportCatalogItemsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'CatalogServiceTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc.py deleted file mode 100644 index 46efec81..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc.py +++ /dev/null @@ -1,412 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.recommendationengine_v1beta1.types import catalog -from google.cloud.recommendationengine_v1beta1.types import catalog_service -from google.cloud.recommendationengine_v1beta1.types import import_ -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO - - -class CatalogServiceGrpcTransport(CatalogServiceTransport): - """gRPC backend transport for CatalogService. - - Service for ingesting catalog information of the customer's - website. - - 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 = 'recommendationengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'recommendationengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_catalog_item(self) -> Callable[ - [catalog_service.CreateCatalogItemRequest], - catalog.CatalogItem]: - r"""Return a callable for the create catalog item method over gRPC. - - Creates a catalog item. - - Returns: - Callable[[~.CreateCatalogItemRequest], - ~.CatalogItem]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog_item' not in self._stubs: - self._stubs['create_catalog_item'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.CatalogService/CreateCatalogItem', - request_serializer=catalog_service.CreateCatalogItemRequest.serialize, - response_deserializer=catalog.CatalogItem.deserialize, - ) - return self._stubs['create_catalog_item'] - - @property - def get_catalog_item(self) -> Callable[ - [catalog_service.GetCatalogItemRequest], - catalog.CatalogItem]: - r"""Return a callable for the get catalog item method over gRPC. - - Gets a specific catalog item. - - Returns: - Callable[[~.GetCatalogItemRequest], - ~.CatalogItem]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog_item' not in self._stubs: - self._stubs['get_catalog_item'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.CatalogService/GetCatalogItem', - request_serializer=catalog_service.GetCatalogItemRequest.serialize, - response_deserializer=catalog.CatalogItem.deserialize, - ) - return self._stubs['get_catalog_item'] - - @property - def list_catalog_items(self) -> Callable[ - [catalog_service.ListCatalogItemsRequest], - catalog_service.ListCatalogItemsResponse]: - r"""Return a callable for the list catalog items method over gRPC. - - Gets a list of catalog items. - - Returns: - Callable[[~.ListCatalogItemsRequest], - ~.ListCatalogItemsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog_items' not in self._stubs: - self._stubs['list_catalog_items'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.CatalogService/ListCatalogItems', - request_serializer=catalog_service.ListCatalogItemsRequest.serialize, - response_deserializer=catalog_service.ListCatalogItemsResponse.deserialize, - ) - return self._stubs['list_catalog_items'] - - @property - def update_catalog_item(self) -> Callable[ - [catalog_service.UpdateCatalogItemRequest], - catalog.CatalogItem]: - r"""Return a callable for the update catalog item method over gRPC. - - Updates a catalog item. Partial updating is - supported. Non-existing items will be created. - - Returns: - Callable[[~.UpdateCatalogItemRequest], - ~.CatalogItem]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog_item' not in self._stubs: - self._stubs['update_catalog_item'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.CatalogService/UpdateCatalogItem', - request_serializer=catalog_service.UpdateCatalogItemRequest.serialize, - response_deserializer=catalog.CatalogItem.deserialize, - ) - return self._stubs['update_catalog_item'] - - @property - def delete_catalog_item(self) -> Callable[ - [catalog_service.DeleteCatalogItemRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete catalog item method over gRPC. - - Deletes a catalog item. - - Returns: - Callable[[~.DeleteCatalogItemRequest], - ~.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_catalog_item' not in self._stubs: - self._stubs['delete_catalog_item'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.CatalogService/DeleteCatalogItem', - request_serializer=catalog_service.DeleteCatalogItemRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_catalog_item'] - - @property - def import_catalog_items(self) -> Callable[ - [import_.ImportCatalogItemsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import catalog items method over gRPC. - - Bulk import of multiple catalog items. Request - processing may be synchronous. No partial updating - supported. Non-existing items will be created. - - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully updated. - - Returns: - Callable[[~.ImportCatalogItemsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog_items' not in self._stubs: - self._stubs['import_catalog_items'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.CatalogService/ImportCatalogItems', - request_serializer=import_.ImportCatalogItemsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_catalog_items'] - - -__all__ = ( - 'CatalogServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc_asyncio.py deleted file mode 100644 index b5e6eba1..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,416 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.recommendationengine_v1beta1.types import catalog -from google.cloud.recommendationengine_v1beta1.types import catalog_service -from google.cloud.recommendationengine_v1beta1.types import import_ -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CatalogServiceGrpcTransport - - -class CatalogServiceGrpcAsyncIOTransport(CatalogServiceTransport): - """gRPC AsyncIO backend transport for CatalogService. - - Service for ingesting catalog information of the customer's - website. - - 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 = 'recommendationengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'recommendationengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_catalog_item(self) -> Callable[ - [catalog_service.CreateCatalogItemRequest], - Awaitable[catalog.CatalogItem]]: - r"""Return a callable for the create catalog item method over gRPC. - - Creates a catalog item. - - Returns: - Callable[[~.CreateCatalogItemRequest], - Awaitable[~.CatalogItem]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog_item' not in self._stubs: - self._stubs['create_catalog_item'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.CatalogService/CreateCatalogItem', - request_serializer=catalog_service.CreateCatalogItemRequest.serialize, - response_deserializer=catalog.CatalogItem.deserialize, - ) - return self._stubs['create_catalog_item'] - - @property - def get_catalog_item(self) -> Callable[ - [catalog_service.GetCatalogItemRequest], - Awaitable[catalog.CatalogItem]]: - r"""Return a callable for the get catalog item method over gRPC. - - Gets a specific catalog item. - - Returns: - Callable[[~.GetCatalogItemRequest], - Awaitable[~.CatalogItem]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog_item' not in self._stubs: - self._stubs['get_catalog_item'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.CatalogService/GetCatalogItem', - request_serializer=catalog_service.GetCatalogItemRequest.serialize, - response_deserializer=catalog.CatalogItem.deserialize, - ) - return self._stubs['get_catalog_item'] - - @property - def list_catalog_items(self) -> Callable[ - [catalog_service.ListCatalogItemsRequest], - Awaitable[catalog_service.ListCatalogItemsResponse]]: - r"""Return a callable for the list catalog items method over gRPC. - - Gets a list of catalog items. - - Returns: - Callable[[~.ListCatalogItemsRequest], - Awaitable[~.ListCatalogItemsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog_items' not in self._stubs: - self._stubs['list_catalog_items'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.CatalogService/ListCatalogItems', - request_serializer=catalog_service.ListCatalogItemsRequest.serialize, - response_deserializer=catalog_service.ListCatalogItemsResponse.deserialize, - ) - return self._stubs['list_catalog_items'] - - @property - def update_catalog_item(self) -> Callable[ - [catalog_service.UpdateCatalogItemRequest], - Awaitable[catalog.CatalogItem]]: - r"""Return a callable for the update catalog item method over gRPC. - - Updates a catalog item. Partial updating is - supported. Non-existing items will be created. - - Returns: - Callable[[~.UpdateCatalogItemRequest], - Awaitable[~.CatalogItem]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_catalog_item' not in self._stubs: - self._stubs['update_catalog_item'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.CatalogService/UpdateCatalogItem', - request_serializer=catalog_service.UpdateCatalogItemRequest.serialize, - response_deserializer=catalog.CatalogItem.deserialize, - ) - return self._stubs['update_catalog_item'] - - @property - def delete_catalog_item(self) -> Callable[ - [catalog_service.DeleteCatalogItemRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete catalog item method over gRPC. - - Deletes a catalog item. - - Returns: - Callable[[~.DeleteCatalogItemRequest], - 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_catalog_item' not in self._stubs: - self._stubs['delete_catalog_item'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.CatalogService/DeleteCatalogItem', - request_serializer=catalog_service.DeleteCatalogItemRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_catalog_item'] - - @property - def import_catalog_items(self) -> Callable[ - [import_.ImportCatalogItemsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import catalog items method over gRPC. - - Bulk import of multiple catalog items. Request - processing may be synchronous. No partial updating - supported. Non-existing items will be created. - - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully updated. - - Returns: - Callable[[~.ImportCatalogItemsRequest], - 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_catalog_items' not in self._stubs: - self._stubs['import_catalog_items'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.CatalogService/ImportCatalogItems', - request_serializer=import_.ImportCatalogItemsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_catalog_items'] - - -__all__ = ( - 'CatalogServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/__init__.py deleted file mode 100644 index d9500520..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import PredictionApiKeyRegistryClient -from .async_client import PredictionApiKeyRegistryAsyncClient - -__all__ = ( - 'PredictionApiKeyRegistryClient', - 'PredictionApiKeyRegistryAsyncClient', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/async_client.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/async_client.py deleted file mode 100644 index 702b4a01..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/async_client.py +++ /dev/null @@ -1,430 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry import pagers -from google.cloud.recommendationengine_v1beta1.types import prediction_apikey_registry_service -from .transports.base import PredictionApiKeyRegistryTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import PredictionApiKeyRegistryGrpcAsyncIOTransport -from .client import PredictionApiKeyRegistryClient - - -class PredictionApiKeyRegistryAsyncClient: - """Service for registering API keys for use with the ``predict`` - method. If you use an API key to request predictions, you must first - register the API key. Otherwise, your prediction request is - rejected. If you use OAuth to authenticate your ``predict`` method - call, you do not need to register an API key. You can register up to - 20 API keys per project. - """ - - _client: PredictionApiKeyRegistryClient - - DEFAULT_ENDPOINT = PredictionApiKeyRegistryClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = PredictionApiKeyRegistryClient.DEFAULT_MTLS_ENDPOINT - - event_store_path = staticmethod(PredictionApiKeyRegistryClient.event_store_path) - parse_event_store_path = staticmethod(PredictionApiKeyRegistryClient.parse_event_store_path) - prediction_api_key_registration_path = staticmethod(PredictionApiKeyRegistryClient.prediction_api_key_registration_path) - parse_prediction_api_key_registration_path = staticmethod(PredictionApiKeyRegistryClient.parse_prediction_api_key_registration_path) - common_billing_account_path = staticmethod(PredictionApiKeyRegistryClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(PredictionApiKeyRegistryClient.parse_common_billing_account_path) - common_folder_path = staticmethod(PredictionApiKeyRegistryClient.common_folder_path) - parse_common_folder_path = staticmethod(PredictionApiKeyRegistryClient.parse_common_folder_path) - common_organization_path = staticmethod(PredictionApiKeyRegistryClient.common_organization_path) - parse_common_organization_path = staticmethod(PredictionApiKeyRegistryClient.parse_common_organization_path) - common_project_path = staticmethod(PredictionApiKeyRegistryClient.common_project_path) - parse_common_project_path = staticmethod(PredictionApiKeyRegistryClient.parse_common_project_path) - common_location_path = staticmethod(PredictionApiKeyRegistryClient.common_location_path) - parse_common_location_path = staticmethod(PredictionApiKeyRegistryClient.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: - PredictionApiKeyRegistryAsyncClient: The constructed client. - """ - return PredictionApiKeyRegistryClient.from_service_account_info.__func__(PredictionApiKeyRegistryAsyncClient, 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: - PredictionApiKeyRegistryAsyncClient: The constructed client. - """ - return PredictionApiKeyRegistryClient.from_service_account_file.__func__(PredictionApiKeyRegistryAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> PredictionApiKeyRegistryTransport: - """Returns the transport used by the client instance. - - Returns: - PredictionApiKeyRegistryTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(PredictionApiKeyRegistryClient).get_transport_class, type(PredictionApiKeyRegistryClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, PredictionApiKeyRegistryTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the prediction api key registry client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.PredictionApiKeyRegistryTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = PredictionApiKeyRegistryClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_prediction_api_key_registration(self, - request: prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest = None, - *, - parent: str = None, - prediction_api_key_registration: prediction_apikey_registry_service.PredictionApiKeyRegistration = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> prediction_apikey_registry_service.PredictionApiKeyRegistration: - r"""Register an API key for use with predict method. - - Args: - request (:class:`google.cloud.recommendationengine_v1beta1.types.CreatePredictionApiKeyRegistrationRequest`): - The request object. Request message for the - `CreatePredictionApiKeyRegistration` method. - parent (:class:`str`): - Required. The parent resource path. - ``projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - prediction_api_key_registration (:class:`google.cloud.recommendationengine_v1beta1.types.PredictionApiKeyRegistration`): - Required. The prediction API key - registration. - - This corresponds to the ``prediction_api_key_registration`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.recommendationengine_v1beta1.types.PredictionApiKeyRegistration: - Registered Api Key. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, prediction_api_key_registration]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if prediction_api_key_registration is not None: - request.prediction_api_key_registration = prediction_api_key_registration - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_prediction_api_key_registration, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_prediction_api_key_registrations(self, - request: prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListPredictionApiKeyRegistrationsAsyncPager: - r"""List the registered apiKeys for use with predict - method. - - Args: - request (:class:`google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsRequest`): - The request object. Request message for the - `ListPredictionApiKeyRegistrations`. - parent (:class:`str`): - Required. The parent placement resource name such as - ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store`` - - 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.recommendationengine_v1beta1.services.prediction_api_key_registry.pagers.ListPredictionApiKeyRegistrationsAsyncPager: - Response message for the - ListPredictionApiKeyRegistrations. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_prediction_api_key_registrations, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListPredictionApiKeyRegistrationsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_prediction_api_key_registration(self, - request: prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Unregister an apiKey from using for predict method. - - Args: - request (:class:`google.cloud.recommendationengine_v1beta1.types.DeletePredictionApiKeyRegistrationRequest`): - The request object. Request message for - `DeletePredictionApiKeyRegistration` method. - name (:class:`str`): - Required. The API key to unregister including full - resource path. - ``projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_prediction_api_key_registration, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-recommendations-ai", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PredictionApiKeyRegistryAsyncClient", -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/client.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/client.py deleted file mode 100644 index cbe8c657..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/client.py +++ /dev/null @@ -1,605 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry import pagers -from google.cloud.recommendationengine_v1beta1.types import prediction_apikey_registry_service -from .transports.base import PredictionApiKeyRegistryTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import PredictionApiKeyRegistryGrpcTransport -from .transports.grpc_asyncio import PredictionApiKeyRegistryGrpcAsyncIOTransport - - -class PredictionApiKeyRegistryClientMeta(type): - """Metaclass for the PredictionApiKeyRegistry 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[PredictionApiKeyRegistryTransport]] - _transport_registry["grpc"] = PredictionApiKeyRegistryGrpcTransport - _transport_registry["grpc_asyncio"] = PredictionApiKeyRegistryGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[PredictionApiKeyRegistryTransport]: - """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 PredictionApiKeyRegistryClient(metaclass=PredictionApiKeyRegistryClientMeta): - """Service for registering API keys for use with the ``predict`` - method. If you use an API key to request predictions, you must first - register the API key. Otherwise, your prediction request is - rejected. If you use OAuth to authenticate your ``predict`` method - call, you do not need to register an API key. You can register up to - 20 API keys per project. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "recommendationengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - PredictionApiKeyRegistryClient: 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: - PredictionApiKeyRegistryClient: 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) -> PredictionApiKeyRegistryTransport: - """Returns the transport used by the client instance. - - Returns: - PredictionApiKeyRegistryTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def event_store_path(project: str,location: str,catalog: str,event_store: str,) -> str: - """Returns a fully-qualified event_store string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}".format(project=project, location=location, catalog=catalog, event_store=event_store, ) - - @staticmethod - def parse_event_store_path(path: str) -> Dict[str,str]: - """Parses a event_store path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/eventStores/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def prediction_api_key_registration_path(project: str,location: str,catalog: str,event_store: str,prediction_api_key_registration: str,) -> str: - """Returns a fully-qualified prediction_api_key_registration string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}/predictionApiKeyRegistrations/{prediction_api_key_registration}".format(project=project, location=location, catalog=catalog, event_store=event_store, prediction_api_key_registration=prediction_api_key_registration, ) - - @staticmethod - def parse_prediction_api_key_registration_path(path: str) -> Dict[str,str]: - """Parses a prediction_api_key_registration path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/eventStores/(?P.+?)/predictionApiKeyRegistrations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, PredictionApiKeyRegistryTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the prediction api key registry client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, PredictionApiKeyRegistryTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, PredictionApiKeyRegistryTransport): - # transport is a PredictionApiKeyRegistryTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def create_prediction_api_key_registration(self, - request: prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest = None, - *, - parent: str = None, - prediction_api_key_registration: prediction_apikey_registry_service.PredictionApiKeyRegistration = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> prediction_apikey_registry_service.PredictionApiKeyRegistration: - r"""Register an API key for use with predict method. - - Args: - request (google.cloud.recommendationengine_v1beta1.types.CreatePredictionApiKeyRegistrationRequest): - The request object. Request message for the - `CreatePredictionApiKeyRegistration` method. - parent (str): - Required. The parent resource path. - ``projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - prediction_api_key_registration (google.cloud.recommendationengine_v1beta1.types.PredictionApiKeyRegistration): - Required. The prediction API key - registration. - - This corresponds to the ``prediction_api_key_registration`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.recommendationengine_v1beta1.types.PredictionApiKeyRegistration: - Registered Api Key. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, prediction_api_key_registration]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest): - request = prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if prediction_api_key_registration is not None: - request.prediction_api_key_registration = prediction_api_key_registration - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_prediction_api_key_registration] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_prediction_api_key_registrations(self, - request: prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListPredictionApiKeyRegistrationsPager: - r"""List the registered apiKeys for use with predict - method. - - Args: - request (google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsRequest): - The request object. Request message for the - `ListPredictionApiKeyRegistrations`. - parent (str): - Required. The parent placement resource name such as - ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store`` - - 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.recommendationengine_v1beta1.services.prediction_api_key_registry.pagers.ListPredictionApiKeyRegistrationsPager: - Response message for the - ListPredictionApiKeyRegistrations. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest): - request = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest(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_prediction_api_key_registrations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListPredictionApiKeyRegistrationsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_prediction_api_key_registration(self, - request: prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Unregister an apiKey from using for predict method. - - Args: - request (google.cloud.recommendationengine_v1beta1.types.DeletePredictionApiKeyRegistrationRequest): - The request object. Request message for - `DeletePredictionApiKeyRegistration` method. - name (str): - Required. The API key to unregister including full - resource path. - ``projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest): - request = prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest(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_prediction_api_key_registration] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-recommendations-ai", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PredictionApiKeyRegistryClient", -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/pagers.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/pagers.py deleted file mode 100644 index e13086de..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.recommendationengine_v1beta1.types import prediction_apikey_registry_service - - -class ListPredictionApiKeyRegistrationsPager: - """A pager for iterating through ``list_prediction_api_key_registrations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``prediction_api_key_registrations`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListPredictionApiKeyRegistrations`` requests and continue to iterate - through the ``prediction_api_key_registrations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsResponse` - 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[..., prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse], - request: prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest, - response: prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse, - *, - 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.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsRequest): - The initial request object. - response (google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsResponse): - 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 = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[prediction_apikey_registry_service.PredictionApiKeyRegistration]: - for page in self.pages: - yield from page.prediction_api_key_registrations - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListPredictionApiKeyRegistrationsAsyncPager: - """A pager for iterating through ``list_prediction_api_key_registrations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``prediction_api_key_registrations`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListPredictionApiKeyRegistrations`` requests and continue to iterate - through the ``prediction_api_key_registrations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsResponse` - 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[prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse]], - request: prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest, - response: prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse, - *, - 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.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsRequest): - The initial request object. - response (google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsResponse): - 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 = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[prediction_apikey_registry_service.PredictionApiKeyRegistration]: - async def async_generator(): - async for page in self.pages: - for response in page.prediction_api_key_registrations: - 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/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/__init__.py deleted file mode 100644 index af3443e5..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import PredictionApiKeyRegistryTransport -from .grpc import PredictionApiKeyRegistryGrpcTransport -from .grpc_asyncio import PredictionApiKeyRegistryGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[PredictionApiKeyRegistryTransport]] -_transport_registry['grpc'] = PredictionApiKeyRegistryGrpcTransport -_transport_registry['grpc_asyncio'] = PredictionApiKeyRegistryGrpcAsyncIOTransport - -__all__ = ( - 'PredictionApiKeyRegistryTransport', - 'PredictionApiKeyRegistryGrpcTransport', - 'PredictionApiKeyRegistryGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/base.py deleted file mode 100644 index daef5afd..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/base.py +++ /dev/null @@ -1,218 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.recommendationengine_v1beta1.types import prediction_apikey_registry_service -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-recommendations-ai', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class PredictionApiKeyRegistryTransport(abc.ABC): - """Abstract transport class for PredictionApiKeyRegistry.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'recommendationengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials is service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_prediction_api_key_registration: gapic_v1.method.wrap_method( - self.create_prediction_api_key_registration, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_prediction_api_key_registrations: gapic_v1.method.wrap_method( - self.list_prediction_api_key_registrations, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.delete_prediction_api_key_registration: gapic_v1.method.wrap_method( - self.delete_prediction_api_key_registration, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - } - - @property - def create_prediction_api_key_registration(self) -> Callable[ - [prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest], - Union[ - prediction_apikey_registry_service.PredictionApiKeyRegistration, - Awaitable[prediction_apikey_registry_service.PredictionApiKeyRegistration] - ]]: - raise NotImplementedError() - - @property - def list_prediction_api_key_registrations(self) -> Callable[ - [prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest], - Union[ - prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse, - Awaitable[prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_prediction_api_key_registration(self) -> Callable[ - [prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'PredictionApiKeyRegistryTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc.py deleted file mode 100644 index aa0feed7..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc.py +++ /dev/null @@ -1,314 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.recommendationengine_v1beta1.types import prediction_apikey_registry_service -from google.protobuf import empty_pb2 # type: ignore -from .base import PredictionApiKeyRegistryTransport, DEFAULT_CLIENT_INFO - - -class PredictionApiKeyRegistryGrpcTransport(PredictionApiKeyRegistryTransport): - """gRPC backend transport for PredictionApiKeyRegistry. - - Service for registering API keys for use with the ``predict`` - method. If you use an API key to request predictions, you must first - register the API key. Otherwise, your prediction request is - rejected. If you use OAuth to authenticate your ``predict`` method - call, you do not need to register an API key. You can register up to - 20 API keys per project. - - 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 = 'recommendationengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'recommendationengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def create_prediction_api_key_registration(self) -> Callable[ - [prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest], - prediction_apikey_registry_service.PredictionApiKeyRegistration]: - r"""Return a callable for the create prediction api key - registration method over gRPC. - - Register an API key for use with predict method. - - Returns: - Callable[[~.CreatePredictionApiKeyRegistrationRequest], - ~.PredictionApiKeyRegistration]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_prediction_api_key_registration' not in self._stubs: - self._stubs['create_prediction_api_key_registration'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry/CreatePredictionApiKeyRegistration', - request_serializer=prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest.serialize, - response_deserializer=prediction_apikey_registry_service.PredictionApiKeyRegistration.deserialize, - ) - return self._stubs['create_prediction_api_key_registration'] - - @property - def list_prediction_api_key_registrations(self) -> Callable[ - [prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest], - prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse]: - r"""Return a callable for the list prediction api key - registrations method over gRPC. - - List the registered apiKeys for use with predict - method. - - Returns: - Callable[[~.ListPredictionApiKeyRegistrationsRequest], - ~.ListPredictionApiKeyRegistrationsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_prediction_api_key_registrations' not in self._stubs: - self._stubs['list_prediction_api_key_registrations'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry/ListPredictionApiKeyRegistrations', - request_serializer=prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest.serialize, - response_deserializer=prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse.deserialize, - ) - return self._stubs['list_prediction_api_key_registrations'] - - @property - def delete_prediction_api_key_registration(self) -> Callable[ - [prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete prediction api key - registration method over gRPC. - - Unregister an apiKey from using for predict method. - - Returns: - Callable[[~.DeletePredictionApiKeyRegistrationRequest], - ~.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_prediction_api_key_registration' not in self._stubs: - self._stubs['delete_prediction_api_key_registration'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry/DeletePredictionApiKeyRegistration', - request_serializer=prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_prediction_api_key_registration'] - - -__all__ = ( - 'PredictionApiKeyRegistryGrpcTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc_asyncio.py deleted file mode 100644 index b00cf102..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc_asyncio.py +++ /dev/null @@ -1,318 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.recommendationengine_v1beta1.types import prediction_apikey_registry_service -from google.protobuf import empty_pb2 # type: ignore -from .base import PredictionApiKeyRegistryTransport, DEFAULT_CLIENT_INFO -from .grpc import PredictionApiKeyRegistryGrpcTransport - - -class PredictionApiKeyRegistryGrpcAsyncIOTransport(PredictionApiKeyRegistryTransport): - """gRPC AsyncIO backend transport for PredictionApiKeyRegistry. - - Service for registering API keys for use with the ``predict`` - method. If you use an API key to request predictions, you must first - register the API key. Otherwise, your prediction request is - rejected. If you use OAuth to authenticate your ``predict`` method - call, you do not need to register an API key. You can register up to - 20 API keys per project. - - 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 = 'recommendationengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'recommendationengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def create_prediction_api_key_registration(self) -> Callable[ - [prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest], - Awaitable[prediction_apikey_registry_service.PredictionApiKeyRegistration]]: - r"""Return a callable for the create prediction api key - registration method over gRPC. - - Register an API key for use with predict method. - - Returns: - Callable[[~.CreatePredictionApiKeyRegistrationRequest], - Awaitable[~.PredictionApiKeyRegistration]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_prediction_api_key_registration' not in self._stubs: - self._stubs['create_prediction_api_key_registration'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry/CreatePredictionApiKeyRegistration', - request_serializer=prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest.serialize, - response_deserializer=prediction_apikey_registry_service.PredictionApiKeyRegistration.deserialize, - ) - return self._stubs['create_prediction_api_key_registration'] - - @property - def list_prediction_api_key_registrations(self) -> Callable[ - [prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest], - Awaitable[prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse]]: - r"""Return a callable for the list prediction api key - registrations method over gRPC. - - List the registered apiKeys for use with predict - method. - - Returns: - Callable[[~.ListPredictionApiKeyRegistrationsRequest], - Awaitable[~.ListPredictionApiKeyRegistrationsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_prediction_api_key_registrations' not in self._stubs: - self._stubs['list_prediction_api_key_registrations'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry/ListPredictionApiKeyRegistrations', - request_serializer=prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest.serialize, - response_deserializer=prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse.deserialize, - ) - return self._stubs['list_prediction_api_key_registrations'] - - @property - def delete_prediction_api_key_registration(self) -> Callable[ - [prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete prediction api key - registration method over gRPC. - - Unregister an apiKey from using for predict method. - - Returns: - Callable[[~.DeletePredictionApiKeyRegistrationRequest], - 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_prediction_api_key_registration' not in self._stubs: - self._stubs['delete_prediction_api_key_registration'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry/DeletePredictionApiKeyRegistration', - request_serializer=prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_prediction_api_key_registration'] - - -__all__ = ( - 'PredictionApiKeyRegistryGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/__init__.py deleted file mode 100644 index 13c5d11c..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import PredictionServiceClient -from .async_client import PredictionServiceAsyncClient - -__all__ = ( - 'PredictionServiceClient', - 'PredictionServiceAsyncClient', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/async_client.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/async_client.py deleted file mode 100644 index b200d750..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/async_client.py +++ /dev/null @@ -1,310 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.recommendationengine_v1beta1.services.prediction_service import pagers -from google.cloud.recommendationengine_v1beta1.types import prediction_service -from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event -from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport -from .client import PredictionServiceClient - - -class PredictionServiceAsyncClient: - """Service for making recommendation prediction.""" - - _client: PredictionServiceClient - - DEFAULT_ENDPOINT = PredictionServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = PredictionServiceClient.DEFAULT_MTLS_ENDPOINT - - placement_path = staticmethod(PredictionServiceClient.placement_path) - parse_placement_path = staticmethod(PredictionServiceClient.parse_placement_path) - common_billing_account_path = staticmethod(PredictionServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(PredictionServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(PredictionServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(PredictionServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(PredictionServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(PredictionServiceClient.parse_common_organization_path) - common_project_path = staticmethod(PredictionServiceClient.common_project_path) - parse_common_project_path = staticmethod(PredictionServiceClient.parse_common_project_path) - common_location_path = staticmethod(PredictionServiceClient.common_location_path) - parse_common_location_path = staticmethod(PredictionServiceClient.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: - PredictionServiceAsyncClient: The constructed client. - """ - return PredictionServiceClient.from_service_account_info.__func__(PredictionServiceAsyncClient, 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: - PredictionServiceAsyncClient: The constructed client. - """ - return PredictionServiceClient.from_service_account_file.__func__(PredictionServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> PredictionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - PredictionServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(PredictionServiceClient).get_transport_class, type(PredictionServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, PredictionServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the prediction service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.PredictionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = PredictionServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def predict(self, - request: prediction_service.PredictRequest = None, - *, - name: str = None, - user_event: gcr_user_event.UserEvent = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.PredictAsyncPager: - r"""Makes a recommendation prediction. If using API Key based - authentication, the API Key must be registered using the - [PredictionApiKeyRegistry][google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry] - service. `Learn - more `__. - - Args: - request (:class:`google.cloud.recommendationengine_v1beta1.types.PredictRequest`): - The request object. Request message for Predict method. - name (:class:`str`): - Required. Full resource name of the format: - ``{name=projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/placements/*}`` - The id of the recommendation engine placement. This id - is used to identify the set of models that will be used - to make the prediction. - - We currently support three placements with the following - IDs by default: - - - ``shopping_cart``: Predicts items frequently bought - together with one or more catalog items in the same - shopping session. Commonly displayed after - ``add-to-cart`` events, on product detail pages, or - on the shopping cart page. - - - ``home_page``: Predicts the next product that a user - will most likely engage with or purchase based on the - shopping or viewing history of the specified - ``userId`` or ``visitorId``. For example - - Recommendations for you. - - - ``product_detail``: Predicts the next product that a - user will most likely engage with or purchase. The - prediction is based on the shopping or viewing - history of the specified ``userId`` or ``visitorId`` - and its relevance to a specified ``CatalogItem``. - Typically used on product detail pages. For example - - More items like this. - - - ``recently_viewed_default``: Returns up to 75 items - recently viewed by the specified ``userId`` or - ``visitorId``, most recent ones first. Returns - nothing if neither of them has viewed any items yet. - For example - Recently viewed. - - The full list of available placements can be seen at - https://console.cloud.google.com/recommendation/datafeeds/default_catalog/dashboard - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - user_event (:class:`google.cloud.recommendationengine_v1beta1.types.UserEvent`): - Required. Context about the user, - what they are looking at and what action - they took to trigger the predict - request. Note that this user event - detail won't be ingested to userEvent - logs. Thus, a separate userEvent write - request is required for event logging. - - This corresponds to the ``user_event`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.recommendationengine_v1beta1.services.prediction_service.pagers.PredictAsyncPager: - Response message for predict method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, user_event]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = prediction_service.PredictRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if user_event is not None: - request.user_event = user_event - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.predict, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.PredictAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-recommendations-ai", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PredictionServiceAsyncClient", -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/client.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/client.py deleted file mode 100644 index 3ad05964..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/client.py +++ /dev/null @@ -1,490 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.recommendationengine_v1beta1.services.prediction_service import pagers -from google.cloud.recommendationengine_v1beta1.types import prediction_service -from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event -from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import PredictionServiceGrpcTransport -from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport - - -class PredictionServiceClientMeta(type): - """Metaclass for the PredictionService 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[PredictionServiceTransport]] - _transport_registry["grpc"] = PredictionServiceGrpcTransport - _transport_registry["grpc_asyncio"] = PredictionServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[PredictionServiceTransport]: - """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 PredictionServiceClient(metaclass=PredictionServiceClientMeta): - """Service for making recommendation prediction.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "recommendationengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - PredictionServiceClient: 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: - PredictionServiceClient: 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) -> PredictionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - PredictionServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def placement_path(project: str,location: str,catalog: str,event_store: str,placement: str,) -> str: - """Returns a fully-qualified placement string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}/placements/{placement}".format(project=project, location=location, catalog=catalog, event_store=event_store, placement=placement, ) - - @staticmethod - def parse_placement_path(path: str) -> Dict[str,str]: - """Parses a placement path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/eventStores/(?P.+?)/placements/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, PredictionServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the prediction service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, PredictionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, PredictionServiceTransport): - # transport is a PredictionServiceTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def predict(self, - request: prediction_service.PredictRequest = None, - *, - name: str = None, - user_event: gcr_user_event.UserEvent = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.PredictPager: - r"""Makes a recommendation prediction. If using API Key based - authentication, the API Key must be registered using the - [PredictionApiKeyRegistry][google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry] - service. `Learn - more `__. - - Args: - request (google.cloud.recommendationengine_v1beta1.types.PredictRequest): - The request object. Request message for Predict method. - name (str): - Required. Full resource name of the format: - ``{name=projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/placements/*}`` - The id of the recommendation engine placement. This id - is used to identify the set of models that will be used - to make the prediction. - - We currently support three placements with the following - IDs by default: - - - ``shopping_cart``: Predicts items frequently bought - together with one or more catalog items in the same - shopping session. Commonly displayed after - ``add-to-cart`` events, on product detail pages, or - on the shopping cart page. - - - ``home_page``: Predicts the next product that a user - will most likely engage with or purchase based on the - shopping or viewing history of the specified - ``userId`` or ``visitorId``. For example - - Recommendations for you. - - - ``product_detail``: Predicts the next product that a - user will most likely engage with or purchase. The - prediction is based on the shopping or viewing - history of the specified ``userId`` or ``visitorId`` - and its relevance to a specified ``CatalogItem``. - Typically used on product detail pages. For example - - More items like this. - - - ``recently_viewed_default``: Returns up to 75 items - recently viewed by the specified ``userId`` or - ``visitorId``, most recent ones first. Returns - nothing if neither of them has viewed any items yet. - For example - Recently viewed. - - The full list of available placements can be seen at - https://console.cloud.google.com/recommendation/datafeeds/default_catalog/dashboard - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - user_event (google.cloud.recommendationengine_v1beta1.types.UserEvent): - Required. Context about the user, - what they are looking at and what action - they took to trigger the predict - request. Note that this user event - detail won't be ingested to userEvent - logs. Thus, a separate userEvent write - request is required for event logging. - - This corresponds to the ``user_event`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.recommendationengine_v1beta1.services.prediction_service.pagers.PredictPager: - Response message for predict method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, user_event]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a prediction_service.PredictRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, prediction_service.PredictRequest): - request = prediction_service.PredictRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if user_event is not None: - request.user_event = user_event - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.predict] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.PredictPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-recommendations-ai", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PredictionServiceClient", -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/pagers.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/pagers.py deleted file mode 100644 index 647d24c7..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.recommendationengine_v1beta1.types import prediction_service - - -class PredictPager: - """A pager for iterating through ``predict`` requests. - - This class thinly wraps an initial - :class:`google.cloud.recommendationengine_v1beta1.types.PredictResponse` object, and - provides an ``__iter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``Predict`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.recommendationengine_v1beta1.types.PredictResponse` - 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[..., prediction_service.PredictResponse], - request: prediction_service.PredictRequest, - response: prediction_service.PredictResponse, - *, - 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.recommendationengine_v1beta1.types.PredictRequest): - The initial request object. - response (google.cloud.recommendationengine_v1beta1.types.PredictResponse): - 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 = prediction_service.PredictRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[prediction_service.PredictResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[prediction_service.PredictResponse.PredictionResult]: - for page in self.pages: - yield from page.results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class PredictAsyncPager: - """A pager for iterating through ``predict`` requests. - - This class thinly wraps an initial - :class:`google.cloud.recommendationengine_v1beta1.types.PredictResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``Predict`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.recommendationengine_v1beta1.types.PredictResponse` - 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[prediction_service.PredictResponse]], - request: prediction_service.PredictRequest, - response: prediction_service.PredictResponse, - *, - 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.recommendationengine_v1beta1.types.PredictRequest): - The initial request object. - response (google.cloud.recommendationengine_v1beta1.types.PredictResponse): - 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 = prediction_service.PredictRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[prediction_service.PredictResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[prediction_service.PredictResponse.PredictionResult]: - async def async_generator(): - async for page in self.pages: - for response in page.results: - 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/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/__init__.py deleted file mode 100644 index d747de2c..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import PredictionServiceTransport -from .grpc import PredictionServiceGrpcTransport -from .grpc_asyncio import PredictionServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[PredictionServiceTransport]] -_transport_registry['grpc'] = PredictionServiceGrpcTransport -_transport_registry['grpc_asyncio'] = PredictionServiceGrpcAsyncIOTransport - -__all__ = ( - 'PredictionServiceTransport', - 'PredictionServiceGrpcTransport', - 'PredictionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/base.py deleted file mode 100644 index 342837c8..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/base.py +++ /dev/null @@ -1,175 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.recommendationengine_v1beta1.types import prediction_service - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-recommendations-ai', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class PredictionServiceTransport(abc.ABC): - """Abstract transport class for PredictionService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'recommendationengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials is service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.predict: gapic_v1.method.wrap_method( - self.predict, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - } - - @property - def predict(self) -> Callable[ - [prediction_service.PredictRequest], - Union[ - prediction_service.PredictResponse, - Awaitable[prediction_service.PredictResponse] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'PredictionServiceTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc.py deleted file mode 100644 index db4532e4..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc.py +++ /dev/null @@ -1,256 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.recommendationengine_v1beta1.types import prediction_service -from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO - - -class PredictionServiceGrpcTransport(PredictionServiceTransport): - """gRPC backend transport for PredictionService. - - Service for making recommendation prediction. - - 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 = 'recommendationengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'recommendationengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def predict(self) -> Callable[ - [prediction_service.PredictRequest], - prediction_service.PredictResponse]: - r"""Return a callable for the predict method over gRPC. - - Makes a recommendation prediction. If using API Key based - authentication, the API Key must be registered using the - [PredictionApiKeyRegistry][google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry] - service. `Learn - more `__. - - Returns: - Callable[[~.PredictRequest], - ~.PredictResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'predict' not in self._stubs: - self._stubs['predict'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.PredictionService/Predict', - request_serializer=prediction_service.PredictRequest.serialize, - response_deserializer=prediction_service.PredictResponse.deserialize, - ) - return self._stubs['predict'] - - -__all__ = ( - 'PredictionServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc_asyncio.py deleted file mode 100644 index 11bd3981..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,260 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.recommendationengine_v1beta1.types import prediction_service -from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import PredictionServiceGrpcTransport - - -class PredictionServiceGrpcAsyncIOTransport(PredictionServiceTransport): - """gRPC AsyncIO backend transport for PredictionService. - - Service for making recommendation prediction. - - 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 = 'recommendationengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'recommendationengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def predict(self) -> Callable[ - [prediction_service.PredictRequest], - Awaitable[prediction_service.PredictResponse]]: - r"""Return a callable for the predict method over gRPC. - - Makes a recommendation prediction. If using API Key based - authentication, the API Key must be registered using the - [PredictionApiKeyRegistry][google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry] - service. `Learn - more `__. - - Returns: - Callable[[~.PredictRequest], - Awaitable[~.PredictResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'predict' not in self._stubs: - self._stubs['predict'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.PredictionService/Predict', - request_serializer=prediction_service.PredictRequest.serialize, - response_deserializer=prediction_service.PredictResponse.deserialize, - ) - return self._stubs['predict'] - - -__all__ = ( - 'PredictionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/__init__.py deleted file mode 100644 index 808f8208..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import UserEventServiceClient -from .async_client import UserEventServiceAsyncClient - -__all__ = ( - 'UserEventServiceClient', - 'UserEventServiceAsyncClient', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/async_client.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/async_client.py deleted file mode 100644 index 99491310..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/async_client.py +++ /dev/null @@ -1,847 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.recommendationengine_v1beta1.services.user_event_service import pagers -from google.cloud.recommendationengine_v1beta1.types import import_ -from google.cloud.recommendationengine_v1beta1.types import user_event -from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event -from google.cloud.recommendationengine_v1beta1.types import user_event_service -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport -from .client import UserEventServiceClient - - -class UserEventServiceAsyncClient: - """Service for ingesting end user actions on the customer - website. - """ - - _client: UserEventServiceClient - - DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT - - event_store_path = staticmethod(UserEventServiceClient.event_store_path) - parse_event_store_path = staticmethod(UserEventServiceClient.parse_event_store_path) - common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) - common_project_path = staticmethod(UserEventServiceClient.common_project_path) - parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) - common_location_path = staticmethod(UserEventServiceClient.common_location_path) - parse_common_location_path = staticmethod(UserEventServiceClient.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: - UserEventServiceAsyncClient: The constructed client. - """ - return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, 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: - UserEventServiceAsyncClient: The constructed client. - """ - return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> UserEventServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserEventServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user event service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.UserEventServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = UserEventServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def write_user_event(self, - request: user_event_service.WriteUserEventRequest = None, - *, - parent: str = None, - user_event: gcr_user_event.UserEvent = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_user_event.UserEvent: - r"""Writes a single user event. - - Args: - request (:class:`google.cloud.recommendationengine_v1beta1.types.WriteUserEventRequest`): - The request object. Request message for WriteUserEvent - method. - parent (:class:`str`): - Required. The parent eventStore resource name, such as - ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - user_event (:class:`google.cloud.recommendationengine_v1beta1.types.UserEvent`): - Required. User event to write. - This corresponds to the ``user_event`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.recommendationengine_v1beta1.types.UserEvent: - UserEvent captures all metadata - information recommendation engine needs - to know about how end users interact - with customers' website. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, user_event]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = user_event_service.WriteUserEventRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if user_event is not None: - request.user_event = user_event - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.write_user_event, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def collect_user_event(self, - request: user_event_service.CollectUserEventRequest = None, - *, - parent: str = None, - user_event: str = None, - uri: str = None, - ets: int = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Recommendations AI - JavaScript pixel. Users should not call this method - directly. - - Args: - request (:class:`google.cloud.recommendationengine_v1beta1.types.CollectUserEventRequest`): - The request object. Request message for CollectUserEvent - method. - parent (:class:`str`): - Required. The parent eventStore name, such as - ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - user_event (:class:`str`): - Required. URL encoded UserEvent - proto. - - This corresponds to the ``user_event`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - uri (:class:`str`): - Optional. The url including cgi- - arameters but excluding the hash - fragment. The URL must be truncated to - 1.5K bytes to conservatively be under - the 2K bytes. This is often more useful - than the referer url, because many - browsers only send the domain for 3rd - party requests. - - This corresponds to the ``uri`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ets (:class:`int`): - Optional. The event timestamp in - milliseconds. This prevents browser - caching of otherwise identical get - requests. The name is abbreviated to - reduce the payload bytes. - - This corresponds to the ``ets`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) returns - (google.api.HttpBody); rpc - UpdateResource(google.api.HttpBody) returns - (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, user_event, uri, ets]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = user_event_service.CollectUserEventRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if user_event is not None: - request.user_event = user_event - if uri is not None: - request.uri = uri - if ets is not None: - request.ets = ets - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.collect_user_event, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_user_events(self, - request: user_event_service.ListUserEventsRequest = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListUserEventsAsyncPager: - r"""Gets a list of user events within a time range, with - potential filtering. - - Args: - request (:class:`google.cloud.recommendationengine_v1beta1.types.ListUserEventsRequest`): - The request object. Request message for ListUserEvents - method. - parent (:class:`str`): - Required. The parent eventStore resource name, such as - ``projects/*/locations/*/catalogs/default_catalog/eventStores/default_event_store``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - Optional. Filtering expression to specify restrictions - over returned events. This is a sequence of terms, where - each term applies some kind of a restriction to the - returned user events. Use this expression to restrict - results to a specific time range, or filter events by - eventType. eg: eventTime > "2012-04-23T18:25:43.511Z" - eventsMissingCatalogItems - eventTime<"2012-04-23T18:25:43.511Z" eventType=search - - We expect only 3 types of fields: - - :: - - * eventTime: this can be specified a maximum of 2 times, once with a - less than operator and once with a greater than operator. The - eventTime restrict should result in one contiguous valid eventTime - range. - - * eventType: only 1 eventType restriction can be specified. - - * eventsMissingCatalogItems: specififying this will restrict results - to events for which catalog items were not found in the catalog. The - default behavior is to return only those events for which catalog - items were found. - - Some examples of valid filters expressions: - - - Example 1: eventTime > "2012-04-23T18:25:43.511Z" - eventTime < "2012-04-23T18:30:43.511Z" - - Example 2: eventTime > "2012-04-23T18:25:43.511Z" - eventType = detail-page-view - - Example 3: eventsMissingCatalogItems eventType = - search eventTime < "2018-04-23T18:30:43.511Z" - - Example 4: eventTime > "2012-04-23T18:25:43.511Z" - - Example 5: eventType = search - - Example 6: eventsMissingCatalogItems - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.recommendationengine_v1beta1.services.user_event_service.pagers.ListUserEventsAsyncPager: - Response message for ListUserEvents - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, filter]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = user_event_service.ListUserEventsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListUserEventsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def purge_user_events(self, - request: user_event_service.PurgeUserEventsRequest = None, - *, - parent: str = None, - filter: str = None, - force: bool = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - Args: - request (:class:`google.cloud.recommendationengine_v1beta1.types.PurgeUserEventsRequest`): - The request object. Request message for PurgeUserEvents - method. - parent (:class:`str`): - Required. The resource name of the event_store under - which the events are created. The format is - ``projects/${projectId}/locations/global/catalogs/${catalogId}/eventStores/${eventStoreId}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - Required. The filter string to specify the events to be - deleted. Empty string filter is not allowed. This filter - can also be used with ListUserEvents API to list events - that will be deleted. The eligible fields for filtering - are: - - - eventType - UserEvent.eventType field of type string. - - eventTime - in ISO 8601 "zulu" format. - - visitorId - field of type string. Specifying this - will delete all events associated with a visitor. - - userId - field of type string. Specifying this will - delete all events associated with a user. Example 1: - Deleting all events in a time range. - ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` - Example 2: Deleting specific eventType in time range. - ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` - Example 3: Deleting all events for a specific visitor - ``visitorId = visitor1024`` The filtering fields are - assumed to have an implicit AND. - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - force (:class:`bool`): - Optional. The default value is false. - Override this flag to true to actually - perform the purge. If the field is not - set to true, a sampling of events to be - deleted will be returned. - - This corresponds to the ``force`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.recommendationengine_v1beta1.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, filter, force]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = user_event_service.PurgeUserEventsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - if force is not None: - request.force = force - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.purge_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - user_event_service.PurgeUserEventsResponse, - metadata_type=user_event_service.PurgeUserEventsMetadata, - ) - - # Done; return the response. - return response - - async def import_user_events(self, - request: import_.ImportUserEventsRequest = None, - *, - parent: str = None, - request_id: str = None, - input_config: import_.InputConfig = None, - errors_config: import_.ImportErrorsConfig = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Args: - request (:class:`google.cloud.recommendationengine_v1beta1.types.ImportUserEventsRequest`): - The request object. Request message for the - ImportUserEvents request. - parent (:class:`str`): - Required. - ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - request_id (:class:`str`): - Optional. Unique identifier provided by client, within - the ancestor dataset scope. Ensures idempotency for - expensive long running operations. Server-generated if - unspecified. Up to 128 characters long. This is returned - as google.longrunning.Operation.name in the response. - Note that this field must not be set if the desired - input config is catalog_inline_source. - - This corresponds to the ``request_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - input_config (:class:`google.cloud.recommendationengine_v1beta1.types.InputConfig`): - Required. The desired input location - of the data. - - This corresponds to the ``input_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - errors_config (:class:`google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig`): - Optional. The desired location of - errors incurred during the Import. - - This corresponds to the ``errors_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.recommendationengine_v1beta1.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is - returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, request_id, input_config, errors_config]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = import_.ImportUserEventsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if request_id is not None: - request.request_id = request_id - if input_config is not None: - request.input_config = input_config - if errors_config is not None: - request.errors_config = errors_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_.ImportUserEventsResponse, - metadata_type=import_.ImportMetadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-recommendations-ai", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "UserEventServiceAsyncClient", -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/client.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/client.py deleted file mode 100644 index c3575cb3..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/client.py +++ /dev/null @@ -1,999 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.recommendationengine_v1beta1.services.user_event_service import pagers -from google.cloud.recommendationengine_v1beta1.types import import_ -from google.cloud.recommendationengine_v1beta1.types import user_event -from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event -from google.cloud.recommendationengine_v1beta1.types import user_event_service -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import UserEventServiceGrpcTransport -from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport - - -class UserEventServiceClientMeta(type): - """Metaclass for the UserEventService 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[UserEventServiceTransport]] - _transport_registry["grpc"] = UserEventServiceGrpcTransport - _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[UserEventServiceTransport]: - """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 UserEventServiceClient(metaclass=UserEventServiceClientMeta): - """Service for ingesting end user actions on the customer - website. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "recommendationengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceClient: 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: - UserEventServiceClient: 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) -> UserEventServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserEventServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def event_store_path(project: str,location: str,catalog: str,event_store: str,) -> str: - """Returns a fully-qualified event_store string.""" - return "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}".format(project=project, location=location, catalog=catalog, event_store=event_store, ) - - @staticmethod - def parse_event_store_path(path: str) -> Dict[str,str]: - """Parses a event_store path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/eventStores/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, UserEventServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user event service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, UserEventServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, UserEventServiceTransport): - # transport is a UserEventServiceTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def write_user_event(self, - request: user_event_service.WriteUserEventRequest = None, - *, - parent: str = None, - user_event: gcr_user_event.UserEvent = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcr_user_event.UserEvent: - r"""Writes a single user event. - - Args: - request (google.cloud.recommendationengine_v1beta1.types.WriteUserEventRequest): - The request object. Request message for WriteUserEvent - method. - parent (str): - Required. The parent eventStore resource name, such as - ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - user_event (google.cloud.recommendationengine_v1beta1.types.UserEvent): - Required. User event to write. - This corresponds to the ``user_event`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.recommendationengine_v1beta1.types.UserEvent: - UserEvent captures all metadata - information recommendation engine needs - to know about how end users interact - with customers' website. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, user_event]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.WriteUserEventRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.WriteUserEventRequest): - request = user_event_service.WriteUserEventRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if user_event is not None: - request.user_event = user_event - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.write_user_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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def collect_user_event(self, - request: user_event_service.CollectUserEventRequest = None, - *, - parent: str = None, - user_event: str = None, - uri: str = None, - ets: int = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Recommendations AI - JavaScript pixel. Users should not call this method - directly. - - Args: - request (google.cloud.recommendationengine_v1beta1.types.CollectUserEventRequest): - The request object. Request message for CollectUserEvent - method. - parent (str): - Required. The parent eventStore name, such as - ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - user_event (str): - Required. URL encoded UserEvent - proto. - - This corresponds to the ``user_event`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - uri (str): - Optional. The url including cgi- - arameters but excluding the hash - fragment. The URL must be truncated to - 1.5K bytes to conservatively be under - the 2K bytes. This is often more useful - than the referer url, because many - browsers only send the domain for 3rd - party requests. - - This corresponds to the ``uri`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ets (int): - Optional. The event timestamp in - milliseconds. This prevents browser - caching of otherwise identical get - requests. The name is abbreviated to - reduce the payload bytes. - - This corresponds to the ``ets`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) returns - (google.api.HttpBody); rpc - UpdateResource(google.api.HttpBody) returns - (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, user_event, uri, ets]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.CollectUserEventRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.CollectUserEventRequest): - request = user_event_service.CollectUserEventRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if user_event is not None: - request.user_event = user_event - if uri is not None: - request.uri = uri - if ets is not None: - request.ets = ets - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.collect_user_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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_user_events(self, - request: user_event_service.ListUserEventsRequest = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListUserEventsPager: - r"""Gets a list of user events within a time range, with - potential filtering. - - Args: - request (google.cloud.recommendationengine_v1beta1.types.ListUserEventsRequest): - The request object. Request message for ListUserEvents - method. - parent (str): - Required. The parent eventStore resource name, such as - ``projects/*/locations/*/catalogs/default_catalog/eventStores/default_event_store``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - Optional. Filtering expression to specify restrictions - over returned events. This is a sequence of terms, where - each term applies some kind of a restriction to the - returned user events. Use this expression to restrict - results to a specific time range, or filter events by - eventType. eg: eventTime > "2012-04-23T18:25:43.511Z" - eventsMissingCatalogItems - eventTime<"2012-04-23T18:25:43.511Z" eventType=search - - We expect only 3 types of fields: - - :: - - * eventTime: this can be specified a maximum of 2 times, once with a - less than operator and once with a greater than operator. The - eventTime restrict should result in one contiguous valid eventTime - range. - - * eventType: only 1 eventType restriction can be specified. - - * eventsMissingCatalogItems: specififying this will restrict results - to events for which catalog items were not found in the catalog. The - default behavior is to return only those events for which catalog - items were found. - - Some examples of valid filters expressions: - - - Example 1: eventTime > "2012-04-23T18:25:43.511Z" - eventTime < "2012-04-23T18:30:43.511Z" - - Example 2: eventTime > "2012-04-23T18:25:43.511Z" - eventType = detail-page-view - - Example 3: eventsMissingCatalogItems eventType = - search eventTime < "2018-04-23T18:30:43.511Z" - - Example 4: eventTime > "2012-04-23T18:25:43.511Z" - - Example 5: eventType = search - - Example 6: eventsMissingCatalogItems - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.recommendationengine_v1beta1.services.user_event_service.pagers.ListUserEventsPager: - Response message for ListUserEvents - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, filter]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.ListUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.ListUserEventsRequest): - request = user_event_service.ListUserEventsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_user_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), - )), - ) - - # 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.ListUserEventsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def purge_user_events(self, - request: user_event_service.PurgeUserEventsRequest = None, - *, - parent: str = None, - filter: str = None, - force: bool = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - Args: - request (google.cloud.recommendationengine_v1beta1.types.PurgeUserEventsRequest): - The request object. Request message for PurgeUserEvents - method. - parent (str): - Required. The resource name of the event_store under - which the events are created. The format is - ``projects/${projectId}/locations/global/catalogs/${catalogId}/eventStores/${eventStoreId}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - Required. The filter string to specify the events to be - deleted. Empty string filter is not allowed. This filter - can also be used with ListUserEvents API to list events - that will be deleted. The eligible fields for filtering - are: - - - eventType - UserEvent.eventType field of type string. - - eventTime - in ISO 8601 "zulu" format. - - visitorId - field of type string. Specifying this - will delete all events associated with a visitor. - - userId - field of type string. Specifying this will - delete all events associated with a user. Example 1: - Deleting all events in a time range. - ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` - Example 2: Deleting specific eventType in time range. - ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` - Example 3: Deleting all events for a specific visitor - ``visitorId = visitor1024`` The filtering fields are - assumed to have an implicit AND. - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - force (bool): - Optional. The default value is false. - Override this flag to true to actually - perform the purge. If the field is not - set to true, a sampling of events to be - deleted will be returned. - - This corresponds to the ``force`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.recommendationengine_v1beta1.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, filter, force]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.PurgeUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.PurgeUserEventsRequest): - request = user_event_service.PurgeUserEventsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - if force is not None: - request.force = force - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.purge_user_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), - )), - ) - - # 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, - user_event_service.PurgeUserEventsResponse, - metadata_type=user_event_service.PurgeUserEventsMetadata, - ) - - # Done; return the response. - return response - - def import_user_events(self, - request: import_.ImportUserEventsRequest = None, - *, - parent: str = None, - request_id: str = None, - input_config: import_.InputConfig = None, - errors_config: import_.ImportErrorsConfig = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Args: - request (google.cloud.recommendationengine_v1beta1.types.ImportUserEventsRequest): - The request object. Request message for the - ImportUserEvents request. - parent (str): - Required. - ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - request_id (str): - Optional. Unique identifier provided by client, within - the ancestor dataset scope. Ensures idempotency for - expensive long running operations. Server-generated if - unspecified. Up to 128 characters long. This is returned - as google.longrunning.Operation.name in the response. - Note that this field must not be set if the desired - input config is catalog_inline_source. - - This corresponds to the ``request_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - input_config (google.cloud.recommendationengine_v1beta1.types.InputConfig): - Required. The desired input location - of the data. - - This corresponds to the ``input_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - errors_config (google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig): - Optional. The desired location of - errors incurred during the Import. - - This corresponds to the ``errors_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout 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.recommendationengine_v1beta1.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is - returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, request_id, input_config, errors_config]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a import_.ImportUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_.ImportUserEventsRequest): - request = import_.ImportUserEventsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if request_id is not None: - request.request_id = request_id - if input_config is not None: - request.input_config = input_config - if errors_config is not None: - request.errors_config = errors_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_user_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), - )), - ) - - # 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, - import_.ImportUserEventsResponse, - metadata_type=import_.ImportMetadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-recommendations-ai", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "UserEventServiceClient", -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/pagers.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/pagers.py deleted file mode 100644 index bea00988..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/pagers.py +++ /dev/null @@ -1,141 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.recommendationengine_v1beta1.types import user_event -from google.cloud.recommendationengine_v1beta1.types import user_event_service - - -class ListUserEventsPager: - """A pager for iterating through ``list_user_events`` requests. - - This class thinly wraps an initial - :class:`google.cloud.recommendationengine_v1beta1.types.ListUserEventsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``user_events`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListUserEvents`` requests and continue to iterate - through the ``user_events`` field on the - corresponding responses. - - All the usual :class:`google.cloud.recommendationengine_v1beta1.types.ListUserEventsResponse` - 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[..., user_event_service.ListUserEventsResponse], - request: user_event_service.ListUserEventsRequest, - response: user_event_service.ListUserEventsResponse, - *, - 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.recommendationengine_v1beta1.types.ListUserEventsRequest): - The initial request object. - response (google.cloud.recommendationengine_v1beta1.types.ListUserEventsResponse): - 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 = user_event_service.ListUserEventsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[user_event_service.ListUserEventsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[user_event.UserEvent]: - for page in self.pages: - yield from page.user_events - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUserEventsAsyncPager: - """A pager for iterating through ``list_user_events`` requests. - - This class thinly wraps an initial - :class:`google.cloud.recommendationengine_v1beta1.types.ListUserEventsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``user_events`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListUserEvents`` requests and continue to iterate - through the ``user_events`` field on the - corresponding responses. - - All the usual :class:`google.cloud.recommendationengine_v1beta1.types.ListUserEventsResponse` - 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[user_event_service.ListUserEventsResponse]], - request: user_event_service.ListUserEventsRequest, - response: user_event_service.ListUserEventsResponse, - *, - 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.recommendationengine_v1beta1.types.ListUserEventsRequest): - The initial request object. - response (google.cloud.recommendationengine_v1beta1.types.ListUserEventsResponse): - 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 = user_event_service.ListUserEventsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[user_event_service.ListUserEventsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[user_event.UserEvent]: - async def async_generator(): - async for page in self.pages: - for response in page.user_events: - 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/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/__init__.py deleted file mode 100644 index 7cff2187..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import UserEventServiceTransport -from .grpc import UserEventServiceGrpcTransport -from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] -_transport_registry['grpc'] = UserEventServiceGrpcTransport -_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport - -__all__ = ( - 'UserEventServiceTransport', - 'UserEventServiceGrpcTransport', - 'UserEventServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/base.py deleted file mode 100644 index 2def0397..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/base.py +++ /dev/null @@ -1,269 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.recommendationengine_v1beta1.types import import_ -from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event -from google.cloud.recommendationengine_v1beta1.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-recommendations-ai', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class UserEventServiceTransport(abc.ABC): - """Abstract transport class for UserEventService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'recommendationengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials is service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.write_user_event: gapic_v1.method.wrap_method( - self.write_user_event, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.collect_user_event: gapic_v1.method.wrap_method( - self.collect_user_event, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_user_events: gapic_v1.method.wrap_method( - self.list_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.purge_user_events: gapic_v1.method.wrap_method( - self.purge_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.import_user_events: gapic_v1.method.wrap_method( - self.import_user_events, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - Union[ - gcr_user_event.UserEvent, - Awaitable[gcr_user_event.UserEvent] - ]]: - raise NotImplementedError() - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - Union[ - httpbody_pb2.HttpBody, - Awaitable[httpbody_pb2.HttpBody] - ]]: - raise NotImplementedError() - - @property - def list_user_events(self) -> Callable[ - [user_event_service.ListUserEventsRequest], - Union[ - user_event_service.ListUserEventsResponse, - Awaitable[user_event_service.ListUserEventsResponse] - ]]: - raise NotImplementedError() - - @property - def purge_user_events(self) -> Callable[ - [user_event_service.PurgeUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def import_user_events(self) -> Callable[ - [import_.ImportUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'UserEventServiceTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc.py deleted file mode 100644 index 28b58907..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc.py +++ /dev/null @@ -1,395 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.recommendationengine_v1beta1.types import import_ -from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event -from google.cloud.recommendationengine_v1beta1.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO - - -class UserEventServiceGrpcTransport(UserEventServiceTransport): - """gRPC backend transport for UserEventService. - - Service for ingesting end user actions on the customer - website. - - 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 = 'recommendationengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'recommendationengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - gcr_user_event.UserEvent]: - r"""Return a callable for the write user event method over gRPC. - - Writes a single user event. - - Returns: - Callable[[~.WriteUserEventRequest], - ~.UserEvent]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'write_user_event' not in self._stubs: - self._stubs['write_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.UserEventService/WriteUserEvent', - request_serializer=user_event_service.WriteUserEventRequest.serialize, - response_deserializer=gcr_user_event.UserEvent.deserialize, - ) - return self._stubs['write_user_event'] - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - httpbody_pb2.HttpBody]: - r"""Return a callable for the collect user event method over gRPC. - - Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Recommendations AI - JavaScript pixel. Users should not call this method - directly. - - Returns: - Callable[[~.CollectUserEventRequest], - ~.HttpBody]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect_user_event' not in self._stubs: - self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.UserEventService/CollectUserEvent', - request_serializer=user_event_service.CollectUserEventRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['collect_user_event'] - - @property - def list_user_events(self) -> Callable[ - [user_event_service.ListUserEventsRequest], - user_event_service.ListUserEventsResponse]: - r"""Return a callable for the list user events method over gRPC. - - Gets a list of user events within a time range, with - potential filtering. - - Returns: - Callable[[~.ListUserEventsRequest], - ~.ListUserEventsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_events' not in self._stubs: - self._stubs['list_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.UserEventService/ListUserEvents', - request_serializer=user_event_service.ListUserEventsRequest.serialize, - response_deserializer=user_event_service.ListUserEventsResponse.deserialize, - ) - return self._stubs['list_user_events'] - - @property - def purge_user_events(self) -> Callable[ - [user_event_service.PurgeUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the purge user events method over gRPC. - - Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - Returns: - Callable[[~.PurgeUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_user_events' not in self._stubs: - self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.UserEventService/PurgeUserEvents', - request_serializer=user_event_service.PurgeUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_user_events'] - - @property - def import_user_events(self) -> Callable[ - [import_.ImportUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import user events method over gRPC. - - Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Returns: - Callable[[~.ImportUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_events' not in self._stubs: - self._stubs['import_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.UserEventService/ImportUserEvents', - request_serializer=import_.ImportUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_user_events'] - - -__all__ = ( - 'UserEventServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc_asyncio.py deleted file mode 100644 index 57e4e84b..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,399 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.recommendationengine_v1beta1.types import import_ -from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event -from google.cloud.recommendationengine_v1beta1.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import UserEventServiceGrpcTransport - - -class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): - """gRPC AsyncIO backend transport for UserEventService. - - Service for ingesting end user actions on the customer - website. - - 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 = 'recommendationengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'recommendationengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - Awaitable[gcr_user_event.UserEvent]]: - r"""Return a callable for the write user event method over gRPC. - - Writes a single user event. - - Returns: - Callable[[~.WriteUserEventRequest], - Awaitable[~.UserEvent]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'write_user_event' not in self._stubs: - self._stubs['write_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.UserEventService/WriteUserEvent', - request_serializer=user_event_service.WriteUserEventRequest.serialize, - response_deserializer=gcr_user_event.UserEvent.deserialize, - ) - return self._stubs['write_user_event'] - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - Awaitable[httpbody_pb2.HttpBody]]: - r"""Return a callable for the collect user event method over gRPC. - - Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a 3rd party domain. - This method is used only by the Recommendations AI - JavaScript pixel. Users should not call this method - directly. - - Returns: - Callable[[~.CollectUserEventRequest], - Awaitable[~.HttpBody]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect_user_event' not in self._stubs: - self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.UserEventService/CollectUserEvent', - request_serializer=user_event_service.CollectUserEventRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['collect_user_event'] - - @property - def list_user_events(self) -> Callable[ - [user_event_service.ListUserEventsRequest], - Awaitable[user_event_service.ListUserEventsResponse]]: - r"""Return a callable for the list user events method over gRPC. - - Gets a list of user events within a time range, with - potential filtering. - - Returns: - Callable[[~.ListUserEventsRequest], - Awaitable[~.ListUserEventsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_events' not in self._stubs: - self._stubs['list_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.UserEventService/ListUserEvents', - request_serializer=user_event_service.ListUserEventsRequest.serialize, - response_deserializer=user_event_service.ListUserEventsResponse.deserialize, - ) - return self._stubs['list_user_events'] - - @property - def purge_user_events(self) -> Callable[ - [user_event_service.PurgeUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the purge user events method over gRPC. - - Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - Returns: - Callable[[~.PurgeUserEventsRequest], - 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 'purge_user_events' not in self._stubs: - self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.UserEventService/PurgeUserEvents', - request_serializer=user_event_service.PurgeUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_user_events'] - - @property - def import_user_events(self) -> Callable[ - [import_.ImportUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import user events method over gRPC. - - Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Returns: - Callable[[~.ImportUserEventsRequest], - 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_user_events' not in self._stubs: - self._stubs['import_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.recommendationengine.v1beta1.UserEventService/ImportUserEvents', - request_serializer=import_.ImportUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_user_events'] - - -__all__ = ( - 'UserEventServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/__init__.py deleted file mode 100644 index c23f7c8a..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/__init__.py +++ /dev/null @@ -1,116 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .catalog import ( - CatalogItem, - Image, - ProductCatalogItem, -) -from .catalog_service import ( - CreateCatalogItemRequest, - DeleteCatalogItemRequest, - GetCatalogItemRequest, - ListCatalogItemsRequest, - ListCatalogItemsResponse, - UpdateCatalogItemRequest, -) -from .common import ( - FeatureMap, -) -from .import_ import ( - CatalogInlineSource, - GcsSource, - ImportCatalogItemsRequest, - ImportCatalogItemsResponse, - ImportErrorsConfig, - ImportMetadata, - ImportUserEventsRequest, - ImportUserEventsResponse, - InputConfig, - UserEventImportSummary, - UserEventInlineSource, -) -from .prediction_apikey_registry_service import ( - CreatePredictionApiKeyRegistrationRequest, - DeletePredictionApiKeyRegistrationRequest, - ListPredictionApiKeyRegistrationsRequest, - ListPredictionApiKeyRegistrationsResponse, - PredictionApiKeyRegistration, -) -from .prediction_service import ( - PredictRequest, - PredictResponse, -) -from .user_event import ( - EventDetail, - ProductDetail, - ProductEventDetail, - PurchaseTransaction, - UserEvent, - UserInfo, -) -from .user_event_service import ( - CollectUserEventRequest, - ListUserEventsRequest, - ListUserEventsResponse, - PurgeUserEventsMetadata, - PurgeUserEventsRequest, - PurgeUserEventsResponse, - WriteUserEventRequest, -) - -__all__ = ( - 'CatalogItem', - 'Image', - 'ProductCatalogItem', - 'CreateCatalogItemRequest', - 'DeleteCatalogItemRequest', - 'GetCatalogItemRequest', - 'ListCatalogItemsRequest', - 'ListCatalogItemsResponse', - 'UpdateCatalogItemRequest', - 'FeatureMap', - 'CatalogInlineSource', - 'GcsSource', - 'ImportCatalogItemsRequest', - 'ImportCatalogItemsResponse', - 'ImportErrorsConfig', - 'ImportMetadata', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'InputConfig', - 'UserEventImportSummary', - 'UserEventInlineSource', - 'CreatePredictionApiKeyRegistrationRequest', - 'DeletePredictionApiKeyRegistrationRequest', - 'ListPredictionApiKeyRegistrationsRequest', - 'ListPredictionApiKeyRegistrationsResponse', - 'PredictionApiKeyRegistration', - 'PredictRequest', - 'PredictResponse', - 'EventDetail', - 'ProductDetail', - 'ProductEventDetail', - 'PurchaseTransaction', - 'UserEvent', - 'UserInfo', - 'CollectUserEventRequest', - 'ListUserEventsRequest', - 'ListUserEventsResponse', - 'PurgeUserEventsMetadata', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - 'WriteUserEventRequest', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/catalog.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/catalog.py deleted file mode 100644 index 11b0fcb9..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/catalog.py +++ /dev/null @@ -1,312 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.recommendationengine_v1beta1.types import common - - -__protobuf__ = proto.module( - package='google.cloud.recommendationengine.v1beta1', - manifest={ - 'CatalogItem', - 'ProductCatalogItem', - 'Image', - }, -) - - -class CatalogItem(proto.Message): - r"""CatalogItem captures all metadata information of items to be - recommended. - - Attributes: - id (str): - Required. Catalog item identifier. UTF-8 - encoded string with a length limit of 128 bytes. - This id must be unique among all catalog items - within the same catalog. It should also be used - when logging user events in order for the user - events to be joined with the Catalog. - category_hierarchies (Sequence[google.cloud.recommendationengine_v1beta1.types.CatalogItem.CategoryHierarchy]): - Required. Catalog item categories. This field is repeated - for supporting one catalog item belonging to several - parallel category hierarchies. - - For example, if a shoes product belongs to both ["Shoes & - Accessories" -> "Shoes"] and ["Sports & Fitness" -> - "Athletic Clothing" -> "Shoes"], it could be represented as: - - :: - - "categoryHierarchies": [ - { "categories": ["Shoes & Accessories", "Shoes"]}, - { "categories": ["Sports & Fitness", "Athletic Clothing", "Shoes"] } - ] - title (str): - Required. Catalog item title. UTF-8 encoded - string with a length limit of 1 KiB. - description (str): - Optional. Catalog item description. UTF-8 - encoded string with a length limit of 5 KiB. - item_attributes (google.cloud.recommendationengine_v1beta1.types.FeatureMap): - Optional. Highly encouraged. Extra catalog - item attributes to be included in the - recommendation model. For example, for retail - products, this could include the store name, - vendor, style, color, etc. These are very strong - signals for recommendation model, thus we highly - recommend providing the item attributes here. - language_code (str): - Optional. Language of the title/description/item_attributes. - Use language tags defined by BCP 47. - https://www.rfc-editor.org/rfc/bcp/bcp47.txt. Our supported - language codes include 'en', 'es', 'fr', 'de', 'ar', 'fa', - 'zh', 'ja', 'ko', 'sv', 'ro', 'nl'. For other languages, - contact your Google account manager. - tags (Sequence[str]): - Optional. Filtering tags associated with the - catalog item. Each tag should be a UTF-8 encoded - string with a length limit of 1 KiB. - This tag can be used for filtering - recommendation results by passing the tag as - part of the predict request filter. - item_group_id (str): - Optional. Variant group identifier for prediction results. - UTF-8 encoded string with a length limit of 128 bytes. - - This field must be enabled before it can be used. `Learn - more `__. - product_metadata (google.cloud.recommendationengine_v1beta1.types.ProductCatalogItem): - Optional. Metadata specific to retail - products. - """ - - class CategoryHierarchy(proto.Message): - r"""Category represents catalog item category hierarchy. - Attributes: - categories (Sequence[str]): - Required. Catalog item categories. Each - category should be a UTF-8 encoded string with a - length limit of 2 KiB. - Note that the order in the list denotes the - specificity (from least to most specific). - """ - - categories = proto.RepeatedField( - proto.STRING, - number=1, - ) - - id = proto.Field( - proto.STRING, - number=1, - ) - category_hierarchies = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=CategoryHierarchy, - ) - title = proto.Field( - proto.STRING, - number=3, - ) - description = proto.Field( - proto.STRING, - number=4, - ) - item_attributes = proto.Field( - proto.MESSAGE, - number=5, - message=common.FeatureMap, - ) - language_code = proto.Field( - proto.STRING, - number=6, - ) - tags = proto.RepeatedField( - proto.STRING, - number=8, - ) - item_group_id = proto.Field( - proto.STRING, - number=9, - ) - product_metadata = proto.Field( - proto.MESSAGE, - number=10, - oneof='recommendation_type', - message='ProductCatalogItem', - ) - - -class ProductCatalogItem(proto.Message): - r"""ProductCatalogItem captures item metadata specific to retail - products. - - Attributes: - exact_price (google.cloud.recommendationengine_v1beta1.types.ProductCatalogItem.ExactPrice): - Optional. The exact product price. - price_range (google.cloud.recommendationengine_v1beta1.types.ProductCatalogItem.PriceRange): - Optional. The product price range. - costs (Sequence[google.cloud.recommendationengine_v1beta1.types.ProductCatalogItem.CostsEntry]): - Optional. A map to pass the costs associated with the - product. - - For example: {"manufacturing": 45.5} The profit of selling - this item is computed like so: - - - If 'exactPrice' is provided, profit = displayPrice - - sum(costs) - - If 'priceRange' is provided, profit = minPrice - - sum(costs) - currency_code (str): - Optional. Only required if the price is set. - Currency code for price/costs. Use three- - character ISO-4217 code. - stock_state (google.cloud.recommendationengine_v1beta1.types.ProductCatalogItem.StockState): - Optional. Online stock state of the catalog item. Default is - ``IN_STOCK``. - available_quantity (int): - Optional. The available quantity of the item. - canonical_product_uri (str): - Optional. Canonical URL directly linking to - the item detail page with a length limit of 5 - KiB.. - images (Sequence[google.cloud.recommendationengine_v1beta1.types.Image]): - Optional. Product images for the catalog - item. - """ - class StockState(proto.Enum): - r"""Item stock state. If this field is unspecified, the item is - assumed to be in stock. - """ - _pb_options = {'allow_alias': True} - STOCK_STATE_UNSPECIFIED = 0 - IN_STOCK = 0 - OUT_OF_STOCK = 1 - PREORDER = 2 - BACKORDER = 3 - - class ExactPrice(proto.Message): - r"""Exact product price. - Attributes: - display_price (float): - Optional. Display price of the product. - original_price (float): - Optional. Price of the product without any - discount. If zero, by default set to be the - 'displayPrice'. - """ - - display_price = proto.Field( - proto.FLOAT, - number=1, - ) - original_price = proto.Field( - proto.FLOAT, - number=2, - ) - - class PriceRange(proto.Message): - r"""Product price range when there are a range of prices for - different variations of the same product. - - Attributes: - min_ (float): - Required. The minimum product price. - max_ (float): - Required. The maximum product price. - """ - - min_ = proto.Field( - proto.FLOAT, - number=1, - ) - max_ = proto.Field( - proto.FLOAT, - number=2, - ) - - exact_price = proto.Field( - proto.MESSAGE, - number=1, - oneof='price', - message=ExactPrice, - ) - price_range = proto.Field( - proto.MESSAGE, - number=2, - oneof='price', - message=PriceRange, - ) - costs = proto.MapField( - proto.STRING, - proto.FLOAT, - number=3, - ) - currency_code = proto.Field( - proto.STRING, - number=4, - ) - stock_state = proto.Field( - proto.ENUM, - number=5, - enum=StockState, - ) - available_quantity = proto.Field( - proto.INT64, - number=6, - ) - canonical_product_uri = proto.Field( - proto.STRING, - number=7, - ) - images = proto.RepeatedField( - proto.MESSAGE, - number=8, - message='Image', - ) - - -class Image(proto.Message): - r"""Catalog item thumbnail/detail image. - Attributes: - uri (str): - Required. URL of the image with a length - limit of 5 KiB. - height (int): - Optional. Height of the image in number of - pixels. - width (int): - Optional. Width of the image in number of - pixels. - """ - - uri = proto.Field( - proto.STRING, - number=1, - ) - height = proto.Field( - proto.INT32, - number=2, - ) - width = proto.Field( - proto.INT32, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/catalog_service.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/catalog_service.py deleted file mode 100644 index 2ebd593e..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/catalog_service.py +++ /dev/null @@ -1,177 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.recommendationengine_v1beta1.types import catalog -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.recommendationengine.v1beta1', - manifest={ - 'CreateCatalogItemRequest', - 'GetCatalogItemRequest', - 'ListCatalogItemsRequest', - 'ListCatalogItemsResponse', - 'UpdateCatalogItemRequest', - 'DeleteCatalogItemRequest', - }, -) - - -class CreateCatalogItemRequest(proto.Message): - r"""Request message for CreateCatalogItem method. - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - catalog_item (google.cloud.recommendationengine_v1beta1.types.CatalogItem): - Required. The catalog item to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - catalog_item = proto.Field( - proto.MESSAGE, - number=2, - message=catalog.CatalogItem, - ) - - -class GetCatalogItemRequest(proto.Message): - r"""Request message for GetCatalogItem method. - Attributes: - name (str): - Required. Full resource name of catalog item, such as - ``projects/*/locations/global/catalogs/default_catalog/catalogitems/some_catalog_item_id``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListCatalogItemsRequest(proto.Message): - r"""Request message for ListCatalogItems method. - Attributes: - parent (str): - Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog``. - page_size (int): - Optional. Maximum number of results to return - per page. If zero, the service will choose a - reasonable default. - page_token (str): - Optional. The previous - ListCatalogItemsResponse.next_page_token. - filter (str): - Optional. A filter to apply on the list - results. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - - -class ListCatalogItemsResponse(proto.Message): - r"""Response message for ListCatalogItems method. - Attributes: - catalog_items (Sequence[google.cloud.recommendationengine_v1beta1.types.CatalogItem]): - The catalog items. - next_page_token (str): - If empty, the list is complete. If nonempty, the token to - pass to the next request's - ListCatalogItemRequest.page_token. - """ - - @property - def raw_page(self): - return self - - catalog_items = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=catalog.CatalogItem, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class UpdateCatalogItemRequest(proto.Message): - r"""Request message for UpdateCatalogItem method. - Attributes: - name (str): - Required. Full resource name of catalog item, such as - "projects/*/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_id". - catalog_item (google.cloud.recommendationengine_v1beta1.types.CatalogItem): - Required. The catalog item to update/create. The - 'catalog_item_id' field has to match that in the 'name'. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Indicates which fields in the - provided 'item' to update. If not set, will by - default update all fields. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - catalog_item = proto.Field( - proto.MESSAGE, - number=2, - message=catalog.CatalogItem, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteCatalogItemRequest(proto.Message): - r"""Request message for DeleteCatalogItem method. - Attributes: - name (str): - Required. Full resource name of catalog item, such as - ``projects/*/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_id``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/common.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/common.py deleted file mode 100644 index f337c80a..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/common.py +++ /dev/null @@ -1,91 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.recommendationengine.v1beta1', - manifest={ - 'FeatureMap', - }, -) - - -class FeatureMap(proto.Message): - r"""FeatureMap represents extra features that customers want to - include in the recommendation model for catalogs/user events as - categorical/numerical features. - - Attributes: - categorical_features (Sequence[google.cloud.recommendationengine_v1beta1.types.FeatureMap.CategoricalFeaturesEntry]): - Categorical features that can take on one of a limited - number of possible values. Some examples would be the - brand/maker of a product, or country of a customer. - - Feature names and values must be UTF-8 encoded strings. - - For example: - ``{ "colors": {"value": ["yellow", "green"]}, "sizes": {"value":["S", "M"]}`` - numerical_features (Sequence[google.cloud.recommendationengine_v1beta1.types.FeatureMap.NumericalFeaturesEntry]): - Numerical features. Some examples would be the height/weight - of a product, or age of a customer. - - Feature names must be UTF-8 encoded strings. - - For example: - ``{ "lengths_cm": {"value":[2.3, 15.4]}, "heights_cm": {"value":[8.1, 6.4]} }`` - """ - - class StringList(proto.Message): - r"""A list of string features. - Attributes: - value (Sequence[str]): - String feature value with a length limit of - 128 bytes. - """ - - value = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class FloatList(proto.Message): - r"""A list of float features. - Attributes: - value (Sequence[float]): - Float feature value. - """ - - value = proto.RepeatedField( - proto.FLOAT, - number=1, - ) - - categorical_features = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=1, - message=StringList, - ) - numerical_features = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message=FloatList, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/import_.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/import_.py deleted file mode 100644 index 292e8400..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/import_.py +++ /dev/null @@ -1,373 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.recommendationengine_v1beta1.types import catalog -from google.cloud.recommendationengine_v1beta1.types import user_event -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.recommendationengine.v1beta1', - manifest={ - 'GcsSource', - 'CatalogInlineSource', - 'UserEventInlineSource', - 'ImportErrorsConfig', - 'ImportCatalogItemsRequest', - 'ImportUserEventsRequest', - 'InputConfig', - 'ImportMetadata', - 'ImportCatalogItemsResponse', - 'ImportUserEventsResponse', - 'UserEventImportSummary', - }, -) - - -class GcsSource(proto.Message): - r"""Google Cloud Storage location for input content. - format. - - Attributes: - input_uris (Sequence[str]): - Required. Google Cloud Storage URIs to input files. URI can - be up to 2000 characters long. URIs can match the full - object path (for example, - ``gs://bucket/directory/object.json``) or a pattern matching - one or more files, such as ``gs://bucket/directory/*.json``. - A request can contain at most 100 files, and each file can - be up to 2 GB. See `Importing catalog - information `__ for - the expected file format and setup instructions. - """ - - input_uris = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class CatalogInlineSource(proto.Message): - r"""The inline source for the input config for ImportCatalogItems - method. - - Attributes: - catalog_items (Sequence[google.cloud.recommendationengine_v1beta1.types.CatalogItem]): - Optional. A list of catalog items to - update/create. Recommended max of 10k items. - """ - - catalog_items = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=catalog.CatalogItem, - ) - - -class UserEventInlineSource(proto.Message): - r"""The inline source for the input config for ImportUserEvents - method. - - Attributes: - user_events (Sequence[google.cloud.recommendationengine_v1beta1.types.UserEvent]): - Optional. A list of user events to import. - Recommended max of 10k items. - """ - - user_events = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=user_event.UserEvent, - ) - - -class ImportErrorsConfig(proto.Message): - r"""Configuration of destination for Import related errors. - Attributes: - gcs_prefix (str): - Google Cloud Storage path for import errors. This must be an - empty, existing Cloud Storage bucket. Import errors will be - written to a file in this bucket, one per line, as a - JSON-encoded ``google.rpc.Status`` message. - """ - - gcs_prefix = proto.Field( - proto.STRING, - number=1, - oneof='destination', - ) - - -class ImportCatalogItemsRequest(proto.Message): - r"""Request message for Import methods. - Attributes: - parent (str): - Required. - ``projects/1234/locations/global/catalogs/default_catalog`` - request_id (str): - Optional. Unique identifier provided by - client, within the ancestor dataset scope. - Ensures idempotency and used for request - deduplication. Server-generated if unspecified. - Up to 128 characters long. This is returned as - google.longrunning.Operation.name in the - response. - input_config (google.cloud.recommendationengine_v1beta1.types.InputConfig): - Required. The desired input location of the - data. - errors_config (google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig): - Optional. The desired location of errors - incurred during the Import. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - request_id = proto.Field( - proto.STRING, - number=2, - ) - input_config = proto.Field( - proto.MESSAGE, - number=3, - message='InputConfig', - ) - errors_config = proto.Field( - proto.MESSAGE, - number=4, - message='ImportErrorsConfig', - ) - - -class ImportUserEventsRequest(proto.Message): - r"""Request message for the ImportUserEvents request. - Attributes: - parent (str): - Required. - ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store`` - request_id (str): - Optional. Unique identifier provided by client, within the - ancestor dataset scope. Ensures idempotency for expensive - long running operations. Server-generated if unspecified. Up - to 128 characters long. This is returned as - google.longrunning.Operation.name in the response. Note that - this field must not be set if the desired input config is - catalog_inline_source. - input_config (google.cloud.recommendationengine_v1beta1.types.InputConfig): - Required. The desired input location of the - data. - errors_config (google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig): - Optional. The desired location of errors - incurred during the Import. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - request_id = proto.Field( - proto.STRING, - number=2, - ) - input_config = proto.Field( - proto.MESSAGE, - number=3, - message='InputConfig', - ) - errors_config = proto.Field( - proto.MESSAGE, - number=4, - message='ImportErrorsConfig', - ) - - -class InputConfig(proto.Message): - r"""The input config source. - Attributes: - catalog_inline_source (google.cloud.recommendationengine_v1beta1.types.CatalogInlineSource): - The Inline source for the input content for - Catalog items. - gcs_source (google.cloud.recommendationengine_v1beta1.types.GcsSource): - Google Cloud Storage location for the input - content. - user_event_inline_source (google.cloud.recommendationengine_v1beta1.types.UserEventInlineSource): - The Inline source for the input content for - UserEvents. - """ - - catalog_inline_source = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='CatalogInlineSource', - ) - gcs_source = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='GcsSource', - ) - user_event_inline_source = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='UserEventInlineSource', - ) - - -class ImportMetadata(proto.Message): - r"""Metadata related to the progress of the Import operation. - This will be returned by the - google.longrunning.Operation.metadata field. - - Attributes: - operation_name (str): - Name of the operation. - request_id (str): - Id of the request / operation. This is - parroting back the requestId that was passed in - the request. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - success_count (int): - Count of entries that were processed - successfully. - failure_count (int): - Count of entries that encountered errors - while processing. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - """ - - operation_name = proto.Field( - proto.STRING, - number=5, - ) - request_id = proto.Field( - proto.STRING, - number=3, - ) - create_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - success_count = proto.Field( - proto.INT64, - number=1, - ) - failure_count = proto.Field( - proto.INT64, - number=2, - ) - update_time = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - - -class ImportCatalogItemsResponse(proto.Message): - r"""Response of the ImportCatalogItemsRequest. If the long - running operation is done, then this message is returned by the - google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig): - Echoes the destination for the complete - errors in the request if set. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ImportErrorsConfig', - ) - - -class ImportUserEventsResponse(proto.Message): - r"""Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is returned by the - google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (Sequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - errors_config (google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig): - Echoes the destination for the complete - errors if this field was set in the request. - import_summary (google.cloud.recommendationengine_v1beta1.types.UserEventImportSummary): - Aggregated statistics of user event import - status. - """ - - error_samples = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - errors_config = proto.Field( - proto.MESSAGE, - number=2, - message='ImportErrorsConfig', - ) - import_summary = proto.Field( - proto.MESSAGE, - number=3, - message='UserEventImportSummary', - ) - - -class UserEventImportSummary(proto.Message): - r"""A summary of import result. The UserEventImportSummary - summarizes the import status for user events. - - Attributes: - joined_events_count (int): - Count of user events imported with complete - existing catalog information. - unjoined_events_count (int): - Count of user events imported, but with - catalog information not found in the imported - catalog. - """ - - joined_events_count = proto.Field( - proto.INT64, - number=1, - ) - unjoined_events_count = proto.Field( - proto.INT64, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/prediction_apikey_registry_service.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/prediction_apikey_registry_service.py deleted file mode 100644 index b0eba7f9..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/prediction_apikey_registry_service.py +++ /dev/null @@ -1,138 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.recommendationengine.v1beta1', - manifest={ - 'PredictionApiKeyRegistration', - 'CreatePredictionApiKeyRegistrationRequest', - 'ListPredictionApiKeyRegistrationsRequest', - 'ListPredictionApiKeyRegistrationsResponse', - 'DeletePredictionApiKeyRegistrationRequest', - }, -) - - -class PredictionApiKeyRegistration(proto.Message): - r"""Registered Api Key. - Attributes: - api_key (str): - The API key. - """ - - api_key = proto.Field( - proto.STRING, - number=1, - ) - - -class CreatePredictionApiKeyRegistrationRequest(proto.Message): - r"""Request message for the ``CreatePredictionApiKeyRegistration`` - method. - - Attributes: - parent (str): - Required. The parent resource path. - ``projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store``. - prediction_api_key_registration (google.cloud.recommendationengine_v1beta1.types.PredictionApiKeyRegistration): - Required. The prediction API key - registration. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - prediction_api_key_registration = proto.Field( - proto.MESSAGE, - number=2, - message='PredictionApiKeyRegistration', - ) - - -class ListPredictionApiKeyRegistrationsRequest(proto.Message): - r"""Request message for the ``ListPredictionApiKeyRegistrations``. - Attributes: - parent (str): - Required. The parent placement resource name such as - ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store`` - page_size (int): - Optional. Maximum number of results to return - per page. If unset, the service will choose a - reasonable default. - page_token (str): - Optional. The previous - ``ListPredictionApiKeyRegistration.nextPageToken``. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListPredictionApiKeyRegistrationsResponse(proto.Message): - r"""Response message for the ``ListPredictionApiKeyRegistrations``. - Attributes: - prediction_api_key_registrations (Sequence[google.cloud.recommendationengine_v1beta1.types.PredictionApiKeyRegistration]): - The list of registered API keys. - next_page_token (str): - If empty, the list is complete. If nonempty, pass the token - to the next request's - ``ListPredictionApiKeysRegistrationsRequest.pageToken``. - """ - - @property - def raw_page(self): - return self - - prediction_api_key_registrations = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='PredictionApiKeyRegistration', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class DeletePredictionApiKeyRegistrationRequest(proto.Message): - r"""Request message for ``DeletePredictionApiKeyRegistration`` method. - Attributes: - name (str): - Required. The API key to unregister including full resource - path. - ``projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/`` - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/prediction_service.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/prediction_service.py deleted file mode 100644 index 3c7988b4..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/prediction_service.py +++ /dev/null @@ -1,271 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.recommendationengine.v1beta1', - manifest={ - 'PredictRequest', - 'PredictResponse', - }, -) - - -class PredictRequest(proto.Message): - r"""Request message for Predict method. - Attributes: - name (str): - Required. Full resource name of the format: - ``{name=projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/placements/*}`` - The id of the recommendation engine placement. This id is - used to identify the set of models that will be used to make - the prediction. - - We currently support three placements with the following IDs - by default: - - - ``shopping_cart``: Predicts items frequently bought - together with one or more catalog items in the same - shopping session. Commonly displayed after - ``add-to-cart`` events, on product detail pages, or on - the shopping cart page. - - - ``home_page``: Predicts the next product that a user will - most likely engage with or purchase based on the shopping - or viewing history of the specified ``userId`` or - ``visitorId``. For example - Recommendations for you. - - - ``product_detail``: Predicts the next product that a user - will most likely engage with or purchase. The prediction - is based on the shopping or viewing history of the - specified ``userId`` or ``visitorId`` and its relevance - to a specified ``CatalogItem``. Typically used on product - detail pages. For example - More items like this. - - - ``recently_viewed_default``: Returns up to 75 items - recently viewed by the specified ``userId`` or - ``visitorId``, most recent ones first. Returns nothing if - neither of them has viewed any items yet. For example - - Recently viewed. - - The full list of available placements can be seen at - https://console.cloud.google.com/recommendation/datafeeds/default_catalog/dashboard - user_event (google.cloud.recommendationengine_v1beta1.types.UserEvent): - Required. Context about the user, what they - are looking at and what action they took to - trigger the predict request. Note that this user - event detail won't be ingested to userEvent - logs. Thus, a separate userEvent write request - is required for event logging. - page_size (int): - Optional. Maximum number of results to return - per page. Set this property to the number of - prediction results required. If zero, the - service will choose a reasonable default. - page_token (str): - Optional. The previous PredictResponse.next_page_token. - filter (str): - Optional. Filter for restricting prediction results. Accepts - values for tags and the ``filterOutOfStockItems`` flag. - - - Tag expressions. Restricts predictions to items that - match all of the specified tags. Boolean operators ``OR`` - and ``NOT`` are supported if the expression is enclosed - in parentheses, and must be separated from the tag values - by a space. ``-"tagA"`` is also supported and is - equivalent to ``NOT "tagA"``. Tag values must be double - quoted UTF-8 encoded strings with a size limit of 1 KiB. - - - filterOutOfStockItems. Restricts predictions to items - that do not have a stockState value of OUT_OF_STOCK. - - Examples: - - - tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT - "promotional") - - filterOutOfStockItems tag=(-"promotional") - - filterOutOfStockItems - dry_run (bool): - Optional. Use dryRun mode for this prediction - query. If set to true, a dummy model will be - used that returns arbitrary catalog items. Note - that the dryRun mode should only be used for - testing the API, or if the model is not ready. - params (Sequence[google.cloud.recommendationengine_v1beta1.types.PredictRequest.ParamsEntry]): - Optional. Additional domain specific parameters for the - predictions. - - Allowed values: - - - ``returnCatalogItem``: Boolean. If set to true, the - associated catalogItem object will be returned in the - ``PredictResponse.PredictionResult.itemMetadata`` object - in the method response. - - ``returnItemScore``: Boolean. If set to true, the - prediction 'score' corresponding to each returned item - will be set in the ``metadata`` field in the prediction - response. The given 'score' indicates the probability of - an item being clicked/purchased given the user's context - and history. - labels (Sequence[google.cloud.recommendationengine_v1beta1.types.PredictRequest.LabelsEntry]): - Optional. The labels for the predict request. - - - Label keys can contain lowercase letters, digits and - hyphens, must start with a letter, and must end with a - letter or digit. - - Non-zero label values can contain lowercase letters, - digits and hyphens, must start with a letter, and must - end with a letter or digit. - - No more than 64 labels can be associated with a given - request. - - See https://goo.gl/xmQnxf for more information on and - examples of labels. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_user_event.UserEvent, - ) - page_size = proto.Field( - proto.INT32, - number=7, - ) - page_token = proto.Field( - proto.STRING, - number=8, - ) - filter = proto.Field( - proto.STRING, - number=3, - ) - dry_run = proto.Field( - proto.BOOL, - number=4, - ) - params = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=6, - message=struct_pb2.Value, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=9, - ) - - -class PredictResponse(proto.Message): - r"""Response message for predict method. - Attributes: - results (Sequence[google.cloud.recommendationengine_v1beta1.types.PredictResponse.PredictionResult]): - A list of recommended items. The order - represents the ranking (from the most relevant - item to the least). - recommendation_token (str): - A unique recommendation token. This should be - included in the user event logs resulting from - this recommendation, which enables accurate - attribution of recommendation model performance. - items_missing_in_catalog (Sequence[str]): - IDs of items in the request that were missing - from the catalog. - dry_run (bool): - True if the dryRun property was set in the - request. - metadata (Sequence[google.cloud.recommendationengine_v1beta1.types.PredictResponse.MetadataEntry]): - Additional domain specific prediction - response metadata. - next_page_token (str): - If empty, the list is complete. If nonempty, the token to - pass to the next request's PredictRequest.page_token. - """ - - class PredictionResult(proto.Message): - r"""PredictionResult represents the recommendation prediction - results. - - Attributes: - id (str): - ID of the recommended catalog item - item_metadata (Sequence[google.cloud.recommendationengine_v1beta1.types.PredictResponse.PredictionResult.ItemMetadataEntry]): - Additional item metadata / annotations. - - Possible values: - - - ``catalogItem``: JSON representation of the catalogItem. - Will be set if ``returnCatalogItem`` is set to true in - ``PredictRequest.params``. - - ``score``: Prediction score in double value. Will be set - if ``returnItemScore`` is set to true in - ``PredictRequest.params``. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - item_metadata = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message=struct_pb2.Value, - ) - - @property - def raw_page(self): - return self - - results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=PredictionResult, - ) - recommendation_token = proto.Field( - proto.STRING, - number=2, - ) - items_missing_in_catalog = proto.RepeatedField( - proto.STRING, - number=3, - ) - dry_run = proto.Field( - proto.BOOL, - number=4, - ) - metadata = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=5, - message=struct_pb2.Value, - ) - next_page_token = proto.Field( - proto.STRING, - number=6, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/recommendationengine_resources.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/recommendationengine_resources.py deleted file mode 100644 index d9dca252..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/recommendationengine_resources.py +++ /dev/null @@ -1,25 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - - -__protobuf__ = proto.module( - package='google.cloud.recommendationengine.v1beta1', - manifest={ - }, -) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/user_event.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/user_event.py deleted file mode 100644 index 111cd038..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/user_event.py +++ /dev/null @@ -1,513 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.recommendationengine_v1beta1.types import catalog -from google.cloud.recommendationengine_v1beta1.types import common -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.recommendationengine.v1beta1', - manifest={ - 'UserEvent', - 'UserInfo', - 'EventDetail', - 'ProductEventDetail', - 'PurchaseTransaction', - 'ProductDetail', - }, -) - - -class UserEvent(proto.Message): - r"""UserEvent captures all metadata information recommendation - engine needs to know about how end users interact with - customers' website. - - Attributes: - event_type (str): - Required. User event type. Allowed values are: - - - ``add-to-cart`` Products being added to cart. - - ``add-to-list`` Items being added to a list (shopping - list, favorites etc). - - ``category-page-view`` Special pages such as sale or - promotion pages viewed. - - ``checkout-start`` User starting a checkout process. - - ``detail-page-view`` Products detail page viewed. - - ``home-page-view`` Homepage viewed. - - ``page-visit`` Generic page visits not included in the - event types above. - - ``purchase-complete`` User finishing a purchase. - - ``refund`` Purchased items being refunded or returned. - - ``remove-from-cart`` Products being removed from cart. - - ``remove-from-list`` Items being removed from a list. - - ``search`` Product search. - - ``shopping-cart-page-view`` User viewing a shopping cart. - - ``impression`` List of items displayed. Used by Google - Tag Manager. - user_info (google.cloud.recommendationengine_v1beta1.types.UserInfo): - Required. User information. - event_detail (google.cloud.recommendationengine_v1beta1.types.EventDetail): - Optional. User event detailed information - common across different recommendation types. - product_event_detail (google.cloud.recommendationengine_v1beta1.types.ProductEventDetail): - Optional. Retail product specific user event metadata. - - This field is required for the following event types: - - - ``add-to-cart`` - - ``add-to-list`` - - ``category-page-view`` - - ``checkout-start`` - - ``detail-page-view`` - - ``purchase-complete`` - - ``refund`` - - ``remove-from-cart`` - - ``remove-from-list`` - - ``search`` - - This field is optional for the following event types: - - - ``page-visit`` - - ``shopping-cart-page-view`` - note that - 'product_event_detail' should be set for this unless the - shopping cart is empty. - - This field is not allowed for the following event types: - - - ``home-page-view`` - event_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. Only required for ImportUserEvents - method. Timestamp of user event created. - event_source (google.cloud.recommendationengine_v1beta1.types.UserEvent.EventSource): - Optional. This field should *not* be set when using - JavaScript pixel or the Recommendations AI Tag. Defaults to - ``EVENT_SOURCE_UNSPECIFIED``. - """ - class EventSource(proto.Enum): - r"""User event source.""" - EVENT_SOURCE_UNSPECIFIED = 0 - AUTOML = 1 - ECOMMERCE = 2 - BATCH_UPLOAD = 3 - - event_type = proto.Field( - proto.STRING, - number=1, - ) - user_info = proto.Field( - proto.MESSAGE, - number=2, - message='UserInfo', - ) - event_detail = proto.Field( - proto.MESSAGE, - number=3, - message='EventDetail', - ) - product_event_detail = proto.Field( - proto.MESSAGE, - number=4, - message='ProductEventDetail', - ) - event_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - event_source = proto.Field( - proto.ENUM, - number=6, - enum=EventSource, - ) - - -class UserInfo(proto.Message): - r"""Information of end users. - Attributes: - visitor_id (str): - Required. A unique identifier for tracking - visitors with a length limit of 128 bytes. - - For example, this could be implemented with a - http cookie, which should be able to uniquely - identify a visitor on a single device. This - unique identifier should not change if the - visitor log in/out of the website. Maximum - length 128 bytes. Cannot be empty. - user_id (str): - Optional. Unique identifier for logged-in - user with a length limit of 128 bytes. Required - only for logged-in users. - ip_address (str): - Optional. IP address of the user. This could be either IPv4 - (e.g. 104.133.9.80) or IPv6 (e.g. - 2001:0db8:85a3:0000:0000:8a2e:0370:7334). This should *not* - be set when using the javascript pixel or if - ``direct_user_request`` is set. Used to extract location - information for personalization. - user_agent (str): - Optional. User agent as included in the HTTP header. UTF-8 - encoded string with a length limit of 1 KiB. - - This should *not* be set when using the JavaScript pixel or - if ``directUserRequest`` is set. - direct_user_request (bool): - Optional. Indicates if the request is made directly from the - end user in which case the user_agent and ip_address fields - can be populated from the HTTP request. This should *not* be - set when using the javascript pixel. This flag should be set - only if the API request is made directly from the end user - such as a mobile app (and not if a gateway or a server is - processing and pushing the user events). - """ - - visitor_id = proto.Field( - proto.STRING, - number=1, - ) - user_id = proto.Field( - proto.STRING, - number=2, - ) - ip_address = proto.Field( - proto.STRING, - number=3, - ) - user_agent = proto.Field( - proto.STRING, - number=4, - ) - direct_user_request = proto.Field( - proto.BOOL, - number=5, - ) - - -class EventDetail(proto.Message): - r"""User event details shared by all recommendation types. - Attributes: - uri (str): - Optional. Complete url (window.location.href) - of the user's current page. When using the - JavaScript pixel, this value is filled in - automatically. Maximum length 5KB. - referrer_uri (str): - Optional. The referrer url of the current - page. When using the JavaScript pixel, this - value is filled in automatically. - page_view_id (str): - Optional. A unique id of a web page view. This should be - kept the same for all user events triggered from the same - pageview. For example, an item detail page view could - trigger multiple events as the user is browsing the page. - The ``pageViewId`` property should be kept the same for all - these events so that they can be grouped together properly. - This ``pageViewId`` will be automatically generated if using - the JavaScript pixel. - experiment_ids (Sequence[str]): - Optional. A list of identifiers for the - independent experiment groups this user event - belongs to. This is used to distinguish between - user events associated with different experiment - setups (e.g. using Recommendation Engine system, - using different recommendation models). - recommendation_token (str): - Optional. Recommendation token included in the - recommendation prediction response. - - This field enables accurate attribution of recommendation - model performance. - - This token enables us to accurately attribute page view or - purchase back to the event and the particular predict - response containing this clicked/purchased item. If user - clicks on product K in the recommendation results, pass the - ``PredictResponse.recommendationToken`` property as a url - parameter to product K's page. When recording events on - product K's page, log the - PredictResponse.recommendation_token to this field. - - Optional, but highly encouraged for user events that are the - result of a recommendation prediction query. - event_attributes (google.cloud.recommendationengine_v1beta1.types.FeatureMap): - Optional. Extra user event features to include in the - recommendation model. - - For product recommendation, an example of extra user - information is traffic_channel, i.e. how user arrives at the - site. Users can arrive at the site by coming to the site - directly, or coming through Google search, and etc. - """ - - uri = proto.Field( - proto.STRING, - number=1, - ) - referrer_uri = proto.Field( - proto.STRING, - number=6, - ) - page_view_id = proto.Field( - proto.STRING, - number=2, - ) - experiment_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - recommendation_token = proto.Field( - proto.STRING, - number=4, - ) - event_attributes = proto.Field( - proto.MESSAGE, - number=5, - message=common.FeatureMap, - ) - - -class ProductEventDetail(proto.Message): - r"""ProductEventDetail captures user event information specific - to retail products. - - Attributes: - search_query (str): - Required for ``search`` events. Other event types should not - set this field. The user's search query as UTF-8 encoded - text with a length limit of 5 KiB. - page_categories (Sequence[google.cloud.recommendationengine_v1beta1.types.CatalogItem.CategoryHierarchy]): - Required for ``category-page-view`` events. Other event - types should not set this field. The categories associated - with a category page. Category pages include special pages - such as sales or promotions. For instance, a special sale - page may have the category hierarchy: categories : ["Sales", - "2017 Black Friday Deals"]. - product_details (Sequence[google.cloud.recommendationengine_v1beta1.types.ProductDetail]): - The main product details related to the event. - - This field is required for the following event types: - - - ``add-to-cart`` - - ``add-to-list`` - - ``checkout-start`` - - ``detail-page-view`` - - ``purchase-complete`` - - ``refund`` - - ``remove-from-cart`` - - ``remove-from-list`` - - This field is optional for the following event types: - - - ``page-visit`` - - ``shopping-cart-page-view`` - note that 'product_details' - should be set for this unless the shopping cart is empty. - - This field is not allowed for the following event types: - - - ``category-page-view`` - - ``home-page-view`` - - ``search`` - list_id (str): - Required for ``add-to-list`` and ``remove-from-list`` - events. The id or name of the list that the item is being - added to or removed from. Other event types should not set - this field. - cart_id (str): - Optional. The id or name of the associated shopping cart. - This id is used to associate multiple items added or present - in the cart before purchase. - - This can only be set for ``add-to-cart``, - ``remove-from-cart``, ``checkout-start``, - ``purchase-complete``, or ``shopping-cart-page-view`` - events. - purchase_transaction (google.cloud.recommendationengine_v1beta1.types.PurchaseTransaction): - Optional. A transaction represents the entire purchase - transaction. Required for ``purchase-complete`` events. - Optional for ``checkout-start`` events. Other event types - should not set this field. - """ - - search_query = proto.Field( - proto.STRING, - number=1, - ) - page_categories = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=catalog.CatalogItem.CategoryHierarchy, - ) - product_details = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='ProductDetail', - ) - list_id = proto.Field( - proto.STRING, - number=4, - ) - cart_id = proto.Field( - proto.STRING, - number=5, - ) - purchase_transaction = proto.Field( - proto.MESSAGE, - number=6, - message='PurchaseTransaction', - ) - - -class PurchaseTransaction(proto.Message): - r"""A transaction represents the entire purchase transaction. - Attributes: - id (str): - Optional. The transaction ID with a length - limit of 128 bytes. - revenue (float): - Required. Total revenue or grand total associated with the - transaction. This value include shipping, tax, or other - adjustments to total revenue that you want to include as - part of your revenue calculations. This field is not - required if the event type is ``refund``. - taxes (Sequence[google.cloud.recommendationengine_v1beta1.types.PurchaseTransaction.TaxesEntry]): - Optional. All the taxes associated with the - transaction. - costs (Sequence[google.cloud.recommendationengine_v1beta1.types.PurchaseTransaction.CostsEntry]): - Optional. All the costs associated with the product. These - can be manufacturing costs, shipping expenses not borne by - the end user, or any other costs. - - Total product cost such that profit = revenue - (sum(taxes) - + sum(costs)) If product_cost is not set, then profit = - revenue - tax - shipping - sum(CatalogItem.costs). - - If CatalogItem.cost is not specified for one of the items, - CatalogItem.cost based profit *cannot* be calculated for - this Transaction. - currency_code (str): - Required. Currency code. Use three-character ISO-4217 code. - This field is not required if the event type is ``refund``. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - revenue = proto.Field( - proto.FLOAT, - number=2, - ) - taxes = proto.MapField( - proto.STRING, - proto.FLOAT, - number=3, - ) - costs = proto.MapField( - proto.STRING, - proto.FLOAT, - number=4, - ) - currency_code = proto.Field( - proto.STRING, - number=6, - ) - - -class ProductDetail(proto.Message): - r"""Detailed product information associated with a user event. - Attributes: - id (str): - Required. Catalog item ID. UTF-8 encoded - string with a length limit of 128 characters. - currency_code (str): - Optional. Currency code for price/costs. Use - three-character ISO-4217 code. Required only if - originalPrice or displayPrice is set. - original_price (float): - Optional. Original price of the product. If - provided, this will override the original price - in Catalog for this product. - display_price (float): - Optional. Display price of the product (e.g. - discounted price). If provided, this will - override the display price in Catalog for this - product. - stock_state (google.cloud.recommendationengine_v1beta1.types.ProductCatalogItem.StockState): - Optional. Item stock state. If provided, this - overrides the stock state in Catalog for items - in this event. - quantity (int): - Optional. Quantity of the product associated with the user - event. For example, this field will be 2 if two products are - added to the shopping cart for ``add-to-cart`` event. - Required for ``add-to-cart``, ``add-to-list``, - ``remove-from-cart``, ``checkout-start``, - ``purchase-complete``, ``refund`` event types. - available_quantity (int): - Optional. Quantity of the products in stock when a user - event happens. Optional. If provided, this overrides the - available quantity in Catalog for this event. and can only - be set if ``stock_status`` is set to ``IN_STOCK``. - - Note that if an item is out of stock, you must set the - ``stock_state`` field to be ``OUT_OF_STOCK``. Leaving this - field unspecified / as zero is not sufficient to mark the - item out of stock. - item_attributes (google.cloud.recommendationengine_v1beta1.types.FeatureMap): - Optional. Extra features associated with a - product in the user event. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - currency_code = proto.Field( - proto.STRING, - number=2, - ) - original_price = proto.Field( - proto.FLOAT, - number=3, - ) - display_price = proto.Field( - proto.FLOAT, - number=4, - ) - stock_state = proto.Field( - proto.ENUM, - number=5, - enum=catalog.ProductCatalogItem.StockState, - ) - quantity = proto.Field( - proto.INT32, - number=6, - ) - available_quantity = proto.Field( - proto.INT32, - number=7, - ) - item_attributes = proto.Field( - proto.MESSAGE, - number=8, - message=common.FeatureMap, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/user_event_service.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/user_event_service.py deleted file mode 100644 index 27e37003..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/user_event_service.py +++ /dev/null @@ -1,289 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.recommendationengine.v1beta1', - manifest={ - 'PurgeUserEventsRequest', - 'PurgeUserEventsMetadata', - 'PurgeUserEventsResponse', - 'WriteUserEventRequest', - 'CollectUserEventRequest', - 'ListUserEventsRequest', - 'ListUserEventsResponse', - }, -) - - -class PurgeUserEventsRequest(proto.Message): - r"""Request message for PurgeUserEvents method. - Attributes: - parent (str): - Required. The resource name of the event_store under which - the events are created. The format is - ``projects/${projectId}/locations/global/catalogs/${catalogId}/eventStores/${eventStoreId}`` - filter (str): - Required. The filter string to specify the events to be - deleted. Empty string filter is not allowed. This filter can - also be used with ListUserEvents API to list events that - will be deleted. The eligible fields for filtering are: - - - eventType - UserEvent.eventType field of type string. - - eventTime - in ISO 8601 "zulu" format. - - visitorId - field of type string. Specifying this will - delete all events associated with a visitor. - - userId - field of type string. Specifying this will - delete all events associated with a user. Example 1: - Deleting all events in a time range. - ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` - Example 2: Deleting specific eventType in time range. - ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` - Example 3: Deleting all events for a specific visitor - ``visitorId = visitor1024`` The filtering fields are - assumed to have an implicit AND. - force (bool): - Optional. The default value is false. - Override this flag to true to actually perform - the purge. If the field is not set to true, a - sampling of events to be deleted will be - returned. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - force = proto.Field( - proto.BOOL, - number=3, - ) - - -class PurgeUserEventsMetadata(proto.Message): - r"""Metadata related to the progress of the PurgeUserEvents - operation. This will be returned by the - google.longrunning.Operation.metadata field. - - Attributes: - operation_name (str): - The ID of the request / operation. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - """ - - operation_name = proto.Field( - proto.STRING, - number=1, - ) - create_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class PurgeUserEventsResponse(proto.Message): - r"""Response of the PurgeUserEventsRequest. If the long running - operation is successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - Attributes: - purged_events_count (int): - The total count of events purged as a result - of the operation. - user_events_sample (Sequence[google.cloud.recommendationengine_v1beta1.types.UserEvent]): - A sampling of events deleted (or will be deleted) depending - on the ``force`` property in the request. Max of 500 items - will be returned. - """ - - purged_events_count = proto.Field( - proto.INT64, - number=1, - ) - user_events_sample = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=gcr_user_event.UserEvent, - ) - - -class WriteUserEventRequest(proto.Message): - r"""Request message for WriteUserEvent method. - Attributes: - parent (str): - Required. The parent eventStore resource name, such as - ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store``. - user_event (google.cloud.recommendationengine_v1beta1.types.UserEvent): - Required. User event to write. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.MESSAGE, - number=2, - message=gcr_user_event.UserEvent, - ) - - -class CollectUserEventRequest(proto.Message): - r"""Request message for CollectUserEvent method. - Attributes: - parent (str): - Required. The parent eventStore name, such as - ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store``. - user_event (str): - Required. URL encoded UserEvent proto. - uri (str): - Optional. The url including cgi-parameters - but excluding the hash fragment. The URL must be - truncated to 1.5K bytes to conservatively be - under the 2K bytes. This is often more useful - than the referer url, because many browsers only - send the domain for 3rd party requests. - ets (int): - Optional. The event timestamp in - milliseconds. This prevents browser caching of - otherwise identical get requests. The name is - abbreviated to reduce the payload bytes. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - user_event = proto.Field( - proto.STRING, - number=2, - ) - uri = proto.Field( - proto.STRING, - number=3, - ) - ets = proto.Field( - proto.INT64, - number=4, - ) - - -class ListUserEventsRequest(proto.Message): - r"""Request message for ListUserEvents method. - Attributes: - parent (str): - Required. The parent eventStore resource name, such as - ``projects/*/locations/*/catalogs/default_catalog/eventStores/default_event_store``. - page_size (int): - Optional. Maximum number of results to return - per page. If zero, the service will choose a - reasonable default. - page_token (str): - Optional. The previous - ListUserEventsResponse.next_page_token. - filter (str): - Optional. Filtering expression to specify restrictions over - returned events. This is a sequence of terms, where each - term applies some kind of a restriction to the returned user - events. Use this expression to restrict results to a - specific time range, or filter events by eventType. eg: - eventTime > "2012-04-23T18:25:43.511Z" - eventsMissingCatalogItems - eventTime<"2012-04-23T18:25:43.511Z" eventType=search - - We expect only 3 types of fields: - - :: - - * eventTime: this can be specified a maximum of 2 times, once with a - less than operator and once with a greater than operator. The - eventTime restrict should result in one contiguous valid eventTime - range. - - * eventType: only 1 eventType restriction can be specified. - - * eventsMissingCatalogItems: specififying this will restrict results - to events for which catalog items were not found in the catalog. The - default behavior is to return only those events for which catalog - items were found. - - Some examples of valid filters expressions: - - - Example 1: eventTime > "2012-04-23T18:25:43.511Z" - eventTime < "2012-04-23T18:30:43.511Z" - - Example 2: eventTime > "2012-04-23T18:25:43.511Z" - eventType = detail-page-view - - Example 3: eventsMissingCatalogItems eventType = search - eventTime < "2018-04-23T18:30:43.511Z" - - Example 4: eventTime > "2012-04-23T18:25:43.511Z" - - Example 5: eventType = search - - Example 6: eventsMissingCatalogItems - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - - -class ListUserEventsResponse(proto.Message): - r"""Response message for ListUserEvents method. - Attributes: - user_events (Sequence[google.cloud.recommendationengine_v1beta1.types.UserEvent]): - The user events. - next_page_token (str): - If empty, the list is complete. If nonempty, the token to - pass to the next request's ListUserEvents.page_token. - """ - - @property - def raw_page(self): - return self - - user_events = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcr_user_event.UserEvent, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/mypy.ini b/owl-bot-staging/v1beta1/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v1beta1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1beta1/noxfile.py b/owl-bot-staging/v1beta1/noxfile.py deleted file mode 100644 index 4cb263a0..00000000 --- a/owl-bot-staging/v1beta1/noxfile.py +++ /dev/null @@ -1,132 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", -] - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/recommendationengine_v1beta1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=['3.6', '3.7']) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python='3.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) diff --git a/owl-bot-staging/v1beta1/scripts/fixup_recommendationengine_v1beta1_keywords.py b/owl-bot-staging/v1beta1/scripts/fixup_recommendationengine_v1beta1_keywords.py deleted file mode 100644 index 9652c971..00000000 --- a/owl-bot-staging/v1beta1/scripts/fixup_recommendationengine_v1beta1_keywords.py +++ /dev/null @@ -1,190 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class recommendationengineCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), - 'create_catalog_item': ('parent', 'catalog_item', ), - 'create_prediction_api_key_registration': ('parent', 'prediction_api_key_registration', ), - 'delete_catalog_item': ('name', ), - 'delete_prediction_api_key_registration': ('name', ), - 'get_catalog_item': ('name', ), - 'import_catalog_items': ('parent', 'input_config', 'request_id', 'errors_config', ), - 'import_user_events': ('parent', 'input_config', 'request_id', 'errors_config', ), - 'list_catalog_items': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_prediction_api_key_registrations': ('parent', 'page_size', 'page_token', ), - 'list_user_events': ('parent', 'page_size', 'page_token', 'filter', ), - 'predict': ('name', 'user_event', 'page_size', 'page_token', 'filter', 'dry_run', 'params', 'labels', ), - 'purge_user_events': ('parent', 'filter', 'force', ), - 'update_catalog_item': ('name', 'catalog_item', 'update_mask', ), - 'write_user_event': ('parent', 'user_event', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: not a.keyword.value in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=recommendationengineCallTransformer(), -): - """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 recommendationengine 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/v1beta1/setup.py b/owl-bot-staging/v1beta1/setup.py deleted file mode 100644 index d9ec7adc..00000000 --- a/owl-bot-staging/v1beta1/setup.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import setuptools # type: ignore - -version = '0.1.0' - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, 'README.rst') -with io.open(readme_filename, encoding='utf-8') as readme_file: - readme = readme_file.read() - -setuptools.setup( - name='google-cloud-recommendations-ai', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.27.0, < 2.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v1beta1/tests/__init__.py b/owl-bot-staging/v1beta1/tests/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1beta1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1beta1/tests/unit/__init__.py b/owl-bot-staging/v1beta1/tests/unit/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1beta1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/__init__.py b/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_catalog_service.py b/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_catalog_service.py deleted file mode 100644 index 86ce00d3..00000000 --- a/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_catalog_service.py +++ /dev/null @@ -1,2676 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.recommendationengine_v1beta1.services.catalog_service import CatalogServiceAsyncClient -from google.cloud.recommendationengine_v1beta1.services.catalog_service import CatalogServiceClient -from google.cloud.recommendationengine_v1beta1.services.catalog_service import pagers -from google.cloud.recommendationengine_v1beta1.services.catalog_service import transports -from google.cloud.recommendationengine_v1beta1.services.catalog_service.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.recommendationengine_v1beta1.types import catalog -from google.cloud.recommendationengine_v1beta1.types import catalog_service -from google.cloud.recommendationengine_v1beta1.types import common -from google.cloud.recommendationengine_v1beta1.types import import_ -from google.cloud.recommendationengine_v1beta1.types import user_event -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert CatalogServiceClient._get_default_mtls_endpoint(None) is None - assert CatalogServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CatalogServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - CatalogServiceClient, - CatalogServiceAsyncClient, -]) -def test_catalog_service_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'recommendationengine.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - CatalogServiceClient, - CatalogServiceAsyncClient, -]) -def test_catalog_service_client_service_account_always_use_jwt(client_class): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - client = client_class(credentials=creds) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CatalogServiceGrpcTransport, "grpc"), - (transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_catalog_service_client_service_account_always_use_jwt_true(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) - - -@pytest.mark.parametrize("client_class", [ - CatalogServiceClient, - CatalogServiceAsyncClient, -]) -def test_catalog_service_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'recommendationengine.googleapis.com:443' - - -def test_catalog_service_client_get_transport_class(): - transport = CatalogServiceClient.get_transport_class() - available_transports = [ - transports.CatalogServiceGrpcTransport, - ] - assert transport in available_transports - - transport = CatalogServiceClient.get_transport_class("grpc") - assert transport == transports.CatalogServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -def test_catalog_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(CatalogServiceClient, '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(CatalogServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "true"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc", "false"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(CatalogServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceClient)) -@mock.patch.object(CatalogServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CatalogServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_catalog_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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_catalog_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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), - (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_catalog_service_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_catalog_service_client_client_options_from_dict(): - with mock.patch('google.cloud.recommendationengine_v1beta1.services.catalog_service.transports.CatalogServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CatalogServiceClient( - 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, - ) - - -def test_create_catalog_item(transport: str = 'grpc', request_type=catalog_service.CreateCatalogItemRequest): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog_item), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CatalogItem( - id='id_value', - title='title_value', - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - item_group_id='item_group_id_value', - product_metadata=catalog.ProductCatalogItem(exact_price=catalog.ProductCatalogItem.ExactPrice(display_price=0.1384)), - ) - response = client.create_catalog_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] == catalog_service.CreateCatalogItemRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CatalogItem) - assert response.id == 'id_value' - assert response.title == 'title_value' - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.item_group_id == 'item_group_id_value' - - -def test_create_catalog_item_from_dict(): - test_create_catalog_item(request_type=dict) - - -def test_create_catalog_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 = CatalogServiceClient( - credentials=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_catalog_item), - '__call__') as call: - client.create_catalog_item() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.CreateCatalogItemRequest() - - -@pytest.mark.asyncio -async def test_create_catalog_item_async(transport: str = 'grpc_asyncio', request_type=catalog_service.CreateCatalogItemRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog_item), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem( - id='id_value', - title='title_value', - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - item_group_id='item_group_id_value', - )) - response = await client.create_catalog_item(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.CreateCatalogItemRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CatalogItem) - assert response.id == 'id_value' - assert response.title == 'title_value' - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.item_group_id == 'item_group_id_value' - - -@pytest.mark.asyncio -async def test_create_catalog_item_async_from_dict(): - await test_create_catalog_item_async(request_type=dict) - - -def test_create_catalog_item_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.CreateCatalogItemRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_catalog_item), - '__call__') as call: - call.return_value = catalog.CatalogItem() - client.create_catalog_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', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_catalog_item_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.CreateCatalogItemRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_catalog_item), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem()) - await client.create_catalog_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', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_create_catalog_item_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_catalog_item), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CatalogItem() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_catalog_item( - parent='parent_value', - catalog_item=catalog.CatalogItem(id='id_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].catalog_item == catalog.CatalogItem(id='id_value') - - -def test_create_catalog_item_flattened_error(): - client = CatalogServiceClient( - credentials=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_catalog_item( - catalog_service.CreateCatalogItemRequest(), - parent='parent_value', - catalog_item=catalog.CatalogItem(id='id_value'), - ) - - -@pytest.mark.asyncio -async def test_create_catalog_item_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_catalog_item), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CatalogItem() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_catalog_item( - parent='parent_value', - catalog_item=catalog.CatalogItem(id='id_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].catalog_item == catalog.CatalogItem(id='id_value') - - -@pytest.mark.asyncio -async def test_create_catalog_item_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_catalog_item( - catalog_service.CreateCatalogItemRequest(), - parent='parent_value', - catalog_item=catalog.CatalogItem(id='id_value'), - ) - - -def test_get_catalog_item(transport: str = 'grpc', request_type=catalog_service.GetCatalogItemRequest): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog_item), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CatalogItem( - id='id_value', - title='title_value', - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - item_group_id='item_group_id_value', - product_metadata=catalog.ProductCatalogItem(exact_price=catalog.ProductCatalogItem.ExactPrice(display_price=0.1384)), - ) - response = client.get_catalog_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] == catalog_service.GetCatalogItemRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CatalogItem) - assert response.id == 'id_value' - assert response.title == 'title_value' - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.item_group_id == 'item_group_id_value' - - -def test_get_catalog_item_from_dict(): - test_get_catalog_item(request_type=dict) - - -def test_get_catalog_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 = CatalogServiceClient( - credentials=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_catalog_item), - '__call__') as call: - client.get_catalog_item() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCatalogItemRequest() - - -@pytest.mark.asyncio -async def test_get_catalog_item_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetCatalogItemRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog_item), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem( - id='id_value', - title='title_value', - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - item_group_id='item_group_id_value', - )) - response = await client.get_catalog_item(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCatalogItemRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CatalogItem) - assert response.id == 'id_value' - assert response.title == 'title_value' - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.item_group_id == 'item_group_id_value' - - -@pytest.mark.asyncio -async def test_get_catalog_item_async_from_dict(): - await test_get_catalog_item_async(request_type=dict) - - -def test_get_catalog_item_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetCatalogItemRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_catalog_item), - '__call__') as call: - call.return_value = catalog.CatalogItem() - client.get_catalog_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', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_catalog_item_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.GetCatalogItemRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_catalog_item), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem()) - await client.get_catalog_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', - 'name=name/value', - ) in kw['metadata'] - - -def test_get_catalog_item_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_catalog_item), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CatalogItem() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_catalog_item( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -def test_get_catalog_item_flattened_error(): - client = CatalogServiceClient( - credentials=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_catalog_item( - catalog_service.GetCatalogItemRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_catalog_item_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_catalog_item), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CatalogItem() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_catalog_item( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_catalog_item_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_catalog_item( - catalog_service.GetCatalogItemRequest(), - name='name_value', - ) - - -def test_list_catalog_items(transport: str = 'grpc', request_type=catalog_service.ListCatalogItemsRequest): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog_items), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogItemsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_catalog_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] == catalog_service.ListCatalogItemsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCatalogItemsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_catalog_items_from_dict(): - test_list_catalog_items(request_type=dict) - - -def test_list_catalog_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 = CatalogServiceClient( - credentials=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_catalog_items), - '__call__') as call: - client.list_catalog_items() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogItemsRequest() - - -@pytest.mark.asyncio -async def test_list_catalog_items_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ListCatalogItemsRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog_items), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogItemsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_catalog_items(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogItemsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCatalogItemsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_catalog_items_async_from_dict(): - await test_list_catalog_items_async(request_type=dict) - - -def test_list_catalog_items_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ListCatalogItemsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalog_items), - '__call__') as call: - call.return_value = catalog_service.ListCatalogItemsResponse() - client.list_catalog_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', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_catalog_items_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.ListCatalogItemsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalog_items), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogItemsResponse()) - await client.list_catalog_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', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_list_catalog_items_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalog_items), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogItemsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_catalog_items( - parent='parent_value', - filter='filter_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].filter == 'filter_value' - - -def test_list_catalog_items_flattened_error(): - client = CatalogServiceClient( - credentials=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_catalog_items( - catalog_service.ListCatalogItemsRequest(), - parent='parent_value', - filter='filter_value', - ) - - -@pytest.mark.asyncio -async def test_list_catalog_items_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalog_items), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog_service.ListCatalogItemsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogItemsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_catalog_items( - parent='parent_value', - filter='filter_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].filter == 'filter_value' - - -@pytest.mark.asyncio -async def test_list_catalog_items_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_catalog_items( - catalog_service.ListCatalogItemsRequest(), - parent='parent_value', - filter='filter_value', - ) - - -def test_list_catalog_items_pager(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalog_items), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogItemsResponse( - catalog_items=[ - catalog.CatalogItem(), - catalog.CatalogItem(), - catalog.CatalogItem(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogItemsResponse( - catalog_items=[], - next_page_token='def', - ), - catalog_service.ListCatalogItemsResponse( - catalog_items=[ - catalog.CatalogItem(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogItemsResponse( - catalog_items=[ - catalog.CatalogItem(), - catalog.CatalogItem(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_catalog_items(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, catalog.CatalogItem) - for i in results) - -def test_list_catalog_items_pages(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalog_items), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogItemsResponse( - catalog_items=[ - catalog.CatalogItem(), - catalog.CatalogItem(), - catalog.CatalogItem(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogItemsResponse( - catalog_items=[], - next_page_token='def', - ), - catalog_service.ListCatalogItemsResponse( - catalog_items=[ - catalog.CatalogItem(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogItemsResponse( - catalog_items=[ - catalog.CatalogItem(), - catalog.CatalogItem(), - ], - ), - RuntimeError, - ) - pages = list(client.list_catalog_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_list_catalog_items_async_pager(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalog_items), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogItemsResponse( - catalog_items=[ - catalog.CatalogItem(), - catalog.CatalogItem(), - catalog.CatalogItem(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogItemsResponse( - catalog_items=[], - next_page_token='def', - ), - catalog_service.ListCatalogItemsResponse( - catalog_items=[ - catalog.CatalogItem(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogItemsResponse( - catalog_items=[ - catalog.CatalogItem(), - catalog.CatalogItem(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_catalog_items(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, catalog.CatalogItem) - for i in responses) - -@pytest.mark.asyncio -async def test_list_catalog_items_async_pages(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalog_items), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - catalog_service.ListCatalogItemsResponse( - catalog_items=[ - catalog.CatalogItem(), - catalog.CatalogItem(), - catalog.CatalogItem(), - ], - next_page_token='abc', - ), - catalog_service.ListCatalogItemsResponse( - catalog_items=[], - next_page_token='def', - ), - catalog_service.ListCatalogItemsResponse( - catalog_items=[ - catalog.CatalogItem(), - ], - next_page_token='ghi', - ), - catalog_service.ListCatalogItemsResponse( - catalog_items=[ - catalog.CatalogItem(), - catalog.CatalogItem(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_catalog_items(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_update_catalog_item(transport: str = 'grpc', request_type=catalog_service.UpdateCatalogItemRequest): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog_item), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CatalogItem( - id='id_value', - title='title_value', - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - item_group_id='item_group_id_value', - product_metadata=catalog.ProductCatalogItem(exact_price=catalog.ProductCatalogItem.ExactPrice(display_price=0.1384)), - ) - response = client.update_catalog_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] == catalog_service.UpdateCatalogItemRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CatalogItem) - assert response.id == 'id_value' - assert response.title == 'title_value' - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.item_group_id == 'item_group_id_value' - - -def test_update_catalog_item_from_dict(): - test_update_catalog_item(request_type=dict) - - -def test_update_catalog_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 = CatalogServiceClient( - credentials=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_catalog_item), - '__call__') as call: - client.update_catalog_item() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogItemRequest() - - -@pytest.mark.asyncio -async def test_update_catalog_item_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCatalogItemRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog_item), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem( - id='id_value', - title='title_value', - description='description_value', - language_code='language_code_value', - tags=['tags_value'], - item_group_id='item_group_id_value', - )) - response = await client.update_catalog_item(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogItemRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CatalogItem) - assert response.id == 'id_value' - assert response.title == 'title_value' - assert response.description == 'description_value' - assert response.language_code == 'language_code_value' - assert response.tags == ['tags_value'] - assert response.item_group_id == 'item_group_id_value' - - -@pytest.mark.asyncio -async def test_update_catalog_item_async_from_dict(): - await test_update_catalog_item_async(request_type=dict) - - -def test_update_catalog_item_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCatalogItemRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog_item), - '__call__') as call: - call.return_value = catalog.CatalogItem() - client.update_catalog_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', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_catalog_item_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.UpdateCatalogItemRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog_item), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem()) - await client.update_catalog_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', - 'name=name/value', - ) in kw['metadata'] - - -def test_update_catalog_item_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog_item), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CatalogItem() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_catalog_item( - name='name_value', - catalog_item=catalog.CatalogItem(id='id_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - assert args[0].catalog_item == catalog.CatalogItem(id='id_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_catalog_item_flattened_error(): - client = CatalogServiceClient( - credentials=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_catalog_item( - catalog_service.UpdateCatalogItemRequest(), - name='name_value', - catalog_item=catalog.CatalogItem(id='id_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_catalog_item_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog_item), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = catalog.CatalogItem() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_catalog_item( - name='name_value', - catalog_item=catalog.CatalogItem(id='id_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - assert args[0].catalog_item == catalog.CatalogItem(id='id_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_catalog_item_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_catalog_item( - catalog_service.UpdateCatalogItemRequest(), - name='name_value', - catalog_item=catalog.CatalogItem(id='id_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_catalog_item(transport: str = 'grpc', request_type=catalog_service.DeleteCatalogItemRequest): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog_item), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_catalog_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] == catalog_service.DeleteCatalogItemRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_catalog_item_from_dict(): - test_delete_catalog_item(request_type=dict) - - -def test_delete_catalog_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 = CatalogServiceClient( - credentials=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_catalog_item), - '__call__') as call: - client.delete_catalog_item() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.DeleteCatalogItemRequest() - - -@pytest.mark.asyncio -async def test_delete_catalog_item_async(transport: str = 'grpc_asyncio', request_type=catalog_service.DeleteCatalogItemRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog_item), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_catalog_item(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.DeleteCatalogItemRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_catalog_item_async_from_dict(): - await test_delete_catalog_item_async(request_type=dict) - - -def test_delete_catalog_item_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.DeleteCatalogItemRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_catalog_item), - '__call__') as call: - call.return_value = None - client.delete_catalog_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', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_catalog_item_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = catalog_service.DeleteCatalogItemRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_catalog_item), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_catalog_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', - 'name=name/value', - ) in kw['metadata'] - - -def test_delete_catalog_item_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_catalog_item), - '__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_catalog_item( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -def test_delete_catalog_item_flattened_error(): - client = CatalogServiceClient( - credentials=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_catalog_item( - catalog_service.DeleteCatalogItemRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_catalog_item_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_catalog_item), - '__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_catalog_item( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_delete_catalog_item_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_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_catalog_item( - catalog_service.DeleteCatalogItemRequest(), - name='name_value', - ) - - -def test_import_catalog_items(transport: str = 'grpc', request_type=import_.ImportCatalogItemsRequest): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog_items), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_catalog_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] == import_.ImportCatalogItemsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_catalog_items_from_dict(): - test_import_catalog_items(request_type=dict) - - -def test_import_catalog_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 = CatalogServiceClient( - credentials=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_catalog_items), - '__call__') as call: - client.import_catalog_items() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_.ImportCatalogItemsRequest() - - -@pytest.mark.asyncio -async def test_import_catalog_items_async(transport: str = 'grpc_asyncio', request_type=import_.ImportCatalogItemsRequest): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_catalog_items), - '__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_catalog_items(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_.ImportCatalogItemsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_catalog_items_async_from_dict(): - await test_import_catalog_items_async(request_type=dict) - - -def test_import_catalog_items_field_headers(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_.ImportCatalogItemsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_catalog_items), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_catalog_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', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_import_catalog_items_field_headers_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_.ImportCatalogItemsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_catalog_items), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_catalog_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', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_import_catalog_items_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_catalog_items), - '__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.import_catalog_items( - parent='parent_value', - request_id='request_id_value', - input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), - errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].request_id == 'request_id_value' - assert args[0].input_config == import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])) - assert args[0].errors_config == import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value') - - -def test_import_catalog_items_flattened_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.import_catalog_items( - import_.ImportCatalogItemsRequest(), - parent='parent_value', - request_id='request_id_value', - input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), - errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), - ) - - -@pytest.mark.asyncio -async def test_import_catalog_items_flattened_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_catalog_items), - '__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.import_catalog_items( - parent='parent_value', - request_id='request_id_value', - input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), - errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].request_id == 'request_id_value' - assert args[0].input_config == import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])) - assert args[0].errors_config == import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value') - - -@pytest.mark.asyncio -async def test_import_catalog_items_flattened_error_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.import_catalog_items( - import_.ImportCatalogItemsRequest(), - parent='parent_value', - request_id='request_id_value', - input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), - errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CatalogServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CatalogServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CatalogServiceGrpcTransport, - ) - -def test_catalog_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CatalogServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_catalog_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.recommendationengine_v1beta1.services.catalog_service.transports.CatalogServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CatalogServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_catalog_item', - 'get_catalog_item', - 'list_catalog_items', - 'update_catalog_item', - 'delete_catalog_item', - 'import_catalog_items', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -def test_catalog_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.recommendationengine_v1beta1.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CatalogServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_catalog_service_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.recommendationengine_v1beta1.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CatalogServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - ), - quota_project_id="octopus", - ) - - -def test_catalog_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.recommendationengine_v1beta1.services.catalog_service.transports.CatalogServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CatalogServiceTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_catalog_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) - CatalogServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_catalog_service_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - CatalogServiceClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_catalog_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.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_catalog_service_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.CatalogServiceGrpcTransport, grpc_helpers), - (transports.CatalogServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_catalog_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( - "recommendationengine.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="recommendationengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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_catalog_service_host_no_port(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='recommendationengine.googleapis.com'), - ) - assert client.transport._host == 'recommendationengine.googleapis.com:443' - - -def test_catalog_service_host_with_port(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='recommendationengine.googleapis.com:8000'), - ) - assert client.transport._host == 'recommendationengine.googleapis.com:8000' - -def test_catalog_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CatalogServiceGrpcTransport( - 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_catalog_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CatalogServiceGrpcAsyncIOTransport( - 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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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.CatalogServiceGrpcTransport, transports.CatalogServiceGrpcAsyncIOTransport]) -def test_catalog_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_catalog_service_grpc_lro_client(): - client = CatalogServiceClient( - 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_catalog_service_grpc_lro_async_client(): - client = CatalogServiceAsyncClient( - 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_catalog_path(): - project = "squid" - location = "clam" - catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format(project=project, location=location, catalog=catalog, ) - actual = CatalogServiceClient.catalog_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_path(): - expected = { - "project": "octopus", - "location": "oyster", - "catalog": "nudibranch", - } - path = CatalogServiceClient.catalog_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_catalog_path(path) - assert expected == actual - -def test_catalog_item_path_path(): - project = "cuttlefish" - location = "mussel" - catalog = "winkle" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/catalogItems/{catalog_item_path=**}".format(project=project, location=location, catalog=catalog, ) - actual = CatalogServiceClient.catalog_item_path_path(project, location, catalog) - assert expected == actual - - -def test_parse_catalog_item_path_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "catalog": "abalone", - } - path = CatalogServiceClient.catalog_item_path_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_catalog_item_path_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CatalogServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = CatalogServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = CatalogServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = CatalogServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CatalogServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = CatalogServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = CatalogServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = CatalogServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.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 = CatalogServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = CatalogServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CatalogServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.CatalogServiceTransport, '_prep_wrapped_messages') as prep: - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CatalogServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CatalogServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_api_key_registry.py b/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_api_key_registry.py deleted file mode 100644 index e44ce0ee..00000000 --- a/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_api_key_registry.py +++ /dev/null @@ -1,1840 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry import PredictionApiKeyRegistryAsyncClient -from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry import PredictionApiKeyRegistryClient -from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry import pagers -from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry import transports -from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.recommendationengine_v1beta1.types import prediction_apikey_registry_service -from google.oauth2 import service_account -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert PredictionApiKeyRegistryClient._get_default_mtls_endpoint(None) is None - assert PredictionApiKeyRegistryClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert PredictionApiKeyRegistryClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert PredictionApiKeyRegistryClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert PredictionApiKeyRegistryClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert PredictionApiKeyRegistryClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - PredictionApiKeyRegistryClient, - PredictionApiKeyRegistryAsyncClient, -]) -def test_prediction_api_key_registry_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'recommendationengine.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - PredictionApiKeyRegistryClient, - PredictionApiKeyRegistryAsyncClient, -]) -def test_prediction_api_key_registry_client_service_account_always_use_jwt(client_class): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - client = client_class(credentials=creds) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.PredictionApiKeyRegistryGrpcTransport, "grpc"), - (transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_prediction_api_key_registry_client_service_account_always_use_jwt_true(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) - - -@pytest.mark.parametrize("client_class", [ - PredictionApiKeyRegistryClient, - PredictionApiKeyRegistryAsyncClient, -]) -def test_prediction_api_key_registry_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'recommendationengine.googleapis.com:443' - - -def test_prediction_api_key_registry_client_get_transport_class(): - transport = PredictionApiKeyRegistryClient.get_transport_class() - available_transports = [ - transports.PredictionApiKeyRegistryGrpcTransport, - ] - assert transport in available_transports - - transport = PredictionApiKeyRegistryClient.get_transport_class("grpc") - assert transport == transports.PredictionApiKeyRegistryGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PredictionApiKeyRegistryClient, transports.PredictionApiKeyRegistryGrpcTransport, "grpc"), - (PredictionApiKeyRegistryAsyncClient, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(PredictionApiKeyRegistryClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionApiKeyRegistryClient)) -@mock.patch.object(PredictionApiKeyRegistryAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionApiKeyRegistryAsyncClient)) -def test_prediction_api_key_registry_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(PredictionApiKeyRegistryClient, '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(PredictionApiKeyRegistryClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (PredictionApiKeyRegistryClient, transports.PredictionApiKeyRegistryGrpcTransport, "grpc", "true"), - (PredictionApiKeyRegistryAsyncClient, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (PredictionApiKeyRegistryClient, transports.PredictionApiKeyRegistryGrpcTransport, "grpc", "false"), - (PredictionApiKeyRegistryAsyncClient, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(PredictionApiKeyRegistryClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionApiKeyRegistryClient)) -@mock.patch.object(PredictionApiKeyRegistryAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionApiKeyRegistryAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_prediction_api_key_registry_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PredictionApiKeyRegistryClient, transports.PredictionApiKeyRegistryGrpcTransport, "grpc"), - (PredictionApiKeyRegistryAsyncClient, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_prediction_api_key_registry_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PredictionApiKeyRegistryClient, transports.PredictionApiKeyRegistryGrpcTransport, "grpc"), - (PredictionApiKeyRegistryAsyncClient, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_prediction_api_key_registry_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_prediction_api_key_registry_client_client_options_from_dict(): - with mock.patch('google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry.transports.PredictionApiKeyRegistryGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = PredictionApiKeyRegistryClient( - 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, - ) - - -def test_create_prediction_api_key_registration(transport: str = 'grpc', request_type=prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest): - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_prediction_api_key_registration), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = prediction_apikey_registry_service.PredictionApiKeyRegistration( - api_key='api_key_value', - ) - response = client.create_prediction_api_key_registration(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, prediction_apikey_registry_service.PredictionApiKeyRegistration) - assert response.api_key == 'api_key_value' - - -def test_create_prediction_api_key_registration_from_dict(): - test_create_prediction_api_key_registration(request_type=dict) - - -def test_create_prediction_api_key_registration_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionApiKeyRegistryClient( - credentials=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_prediction_api_key_registration), - '__call__') as call: - client.create_prediction_api_key_registration() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() - - -@pytest.mark.asyncio -async def test_create_prediction_api_key_registration_async(transport: str = 'grpc_asyncio', request_type=prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest): - client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_prediction_api_key_registration), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(prediction_apikey_registry_service.PredictionApiKeyRegistration( - api_key='api_key_value', - )) - response = await client.create_prediction_api_key_registration(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, prediction_apikey_registry_service.PredictionApiKeyRegistration) - assert response.api_key == 'api_key_value' - - -@pytest.mark.asyncio -async def test_create_prediction_api_key_registration_async_from_dict(): - await test_create_prediction_api_key_registration_async(request_type=dict) - - -def test_create_prediction_api_key_registration_field_headers(): - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_prediction_api_key_registration), - '__call__') as call: - call.return_value = prediction_apikey_registry_service.PredictionApiKeyRegistration() - client.create_prediction_api_key_registration(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_prediction_api_key_registration_field_headers_async(): - client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_prediction_api_key_registration), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_apikey_registry_service.PredictionApiKeyRegistration()) - await client.create_prediction_api_key_registration(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_prediction_api_key_registration_flattened(): - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_prediction_api_key_registration), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = prediction_apikey_registry_service.PredictionApiKeyRegistration() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_prediction_api_key_registration( - parent='parent_value', - prediction_api_key_registration=prediction_apikey_registry_service.PredictionApiKeyRegistration(api_key='api_key_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].prediction_api_key_registration == prediction_apikey_registry_service.PredictionApiKeyRegistration(api_key='api_key_value') - - -def test_create_prediction_api_key_registration_flattened_error(): - client = PredictionApiKeyRegistryClient( - credentials=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_prediction_api_key_registration( - prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest(), - parent='parent_value', - prediction_api_key_registration=prediction_apikey_registry_service.PredictionApiKeyRegistration(api_key='api_key_value'), - ) - - -@pytest.mark.asyncio -async def test_create_prediction_api_key_registration_flattened_async(): - client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_prediction_api_key_registration), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = prediction_apikey_registry_service.PredictionApiKeyRegistration() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_apikey_registry_service.PredictionApiKeyRegistration()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_prediction_api_key_registration( - parent='parent_value', - prediction_api_key_registration=prediction_apikey_registry_service.PredictionApiKeyRegistration(api_key='api_key_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].prediction_api_key_registration == prediction_apikey_registry_service.PredictionApiKeyRegistration(api_key='api_key_value') - - -@pytest.mark.asyncio -async def test_create_prediction_api_key_registration_flattened_error_async(): - client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_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_prediction_api_key_registration( - prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest(), - parent='parent_value', - prediction_api_key_registration=prediction_apikey_registry_service.PredictionApiKeyRegistration(api_key='api_key_value'), - ) - - -def test_list_prediction_api_key_registrations(transport: str = 'grpc', request_type=prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest): - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_prediction_api_key_registrations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_prediction_api_key_registrations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPredictionApiKeyRegistrationsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_prediction_api_key_registrations_from_dict(): - test_list_prediction_api_key_registrations(request_type=dict) - - -def test_list_prediction_api_key_registrations_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionApiKeyRegistryClient( - credentials=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_prediction_api_key_registrations), - '__call__') as call: - client.list_prediction_api_key_registrations() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() - - -@pytest.mark.asyncio -async def test_list_prediction_api_key_registrations_async(transport: str = 'grpc_asyncio', request_type=prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest): - client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_prediction_api_key_registrations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_prediction_api_key_registrations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPredictionApiKeyRegistrationsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_prediction_api_key_registrations_async_from_dict(): - await test_list_prediction_api_key_registrations_async(request_type=dict) - - -def test_list_prediction_api_key_registrations_field_headers(): - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_prediction_api_key_registrations), - '__call__') as call: - call.return_value = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse() - client.list_prediction_api_key_registrations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_prediction_api_key_registrations_field_headers_async(): - client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_prediction_api_key_registrations), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse()) - await client.list_prediction_api_key_registrations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_prediction_api_key_registrations_flattened(): - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_prediction_api_key_registrations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_prediction_api_key_registrations( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -def test_list_prediction_api_key_registrations_flattened_error(): - client = PredictionApiKeyRegistryClient( - credentials=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_prediction_api_key_registrations( - prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_prediction_api_key_registrations_flattened_async(): - client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_prediction_api_key_registrations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_prediction_api_key_registrations( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_prediction_api_key_registrations_flattened_error_async(): - client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_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_prediction_api_key_registrations( - prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest(), - parent='parent_value', - ) - - -def test_list_prediction_api_key_registrations_pager(): - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_prediction_api_key_registrations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( - prediction_api_key_registrations=[ - prediction_apikey_registry_service.PredictionApiKeyRegistration(), - prediction_apikey_registry_service.PredictionApiKeyRegistration(), - prediction_apikey_registry_service.PredictionApiKeyRegistration(), - ], - next_page_token='abc', - ), - prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( - prediction_api_key_registrations=[], - next_page_token='def', - ), - prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( - prediction_api_key_registrations=[ - prediction_apikey_registry_service.PredictionApiKeyRegistration(), - ], - next_page_token='ghi', - ), - prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( - prediction_api_key_registrations=[ - prediction_apikey_registry_service.PredictionApiKeyRegistration(), - prediction_apikey_registry_service.PredictionApiKeyRegistration(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_prediction_api_key_registrations(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, prediction_apikey_registry_service.PredictionApiKeyRegistration) - for i in results) - -def test_list_prediction_api_key_registrations_pages(): - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_prediction_api_key_registrations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( - prediction_api_key_registrations=[ - prediction_apikey_registry_service.PredictionApiKeyRegistration(), - prediction_apikey_registry_service.PredictionApiKeyRegistration(), - prediction_apikey_registry_service.PredictionApiKeyRegistration(), - ], - next_page_token='abc', - ), - prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( - prediction_api_key_registrations=[], - next_page_token='def', - ), - prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( - prediction_api_key_registrations=[ - prediction_apikey_registry_service.PredictionApiKeyRegistration(), - ], - next_page_token='ghi', - ), - prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( - prediction_api_key_registrations=[ - prediction_apikey_registry_service.PredictionApiKeyRegistration(), - prediction_apikey_registry_service.PredictionApiKeyRegistration(), - ], - ), - RuntimeError, - ) - pages = list(client.list_prediction_api_key_registrations(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_prediction_api_key_registrations_async_pager(): - client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_prediction_api_key_registrations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( - prediction_api_key_registrations=[ - prediction_apikey_registry_service.PredictionApiKeyRegistration(), - prediction_apikey_registry_service.PredictionApiKeyRegistration(), - prediction_apikey_registry_service.PredictionApiKeyRegistration(), - ], - next_page_token='abc', - ), - prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( - prediction_api_key_registrations=[], - next_page_token='def', - ), - prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( - prediction_api_key_registrations=[ - prediction_apikey_registry_service.PredictionApiKeyRegistration(), - ], - next_page_token='ghi', - ), - prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( - prediction_api_key_registrations=[ - prediction_apikey_registry_service.PredictionApiKeyRegistration(), - prediction_apikey_registry_service.PredictionApiKeyRegistration(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_prediction_api_key_registrations(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, prediction_apikey_registry_service.PredictionApiKeyRegistration) - for i in responses) - -@pytest.mark.asyncio -async def test_list_prediction_api_key_registrations_async_pages(): - client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_prediction_api_key_registrations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( - prediction_api_key_registrations=[ - prediction_apikey_registry_service.PredictionApiKeyRegistration(), - prediction_apikey_registry_service.PredictionApiKeyRegistration(), - prediction_apikey_registry_service.PredictionApiKeyRegistration(), - ], - next_page_token='abc', - ), - prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( - prediction_api_key_registrations=[], - next_page_token='def', - ), - prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( - prediction_api_key_registrations=[ - prediction_apikey_registry_service.PredictionApiKeyRegistration(), - ], - next_page_token='ghi', - ), - prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( - prediction_api_key_registrations=[ - prediction_apikey_registry_service.PredictionApiKeyRegistration(), - prediction_apikey_registry_service.PredictionApiKeyRegistration(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_prediction_api_key_registrations(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_delete_prediction_api_key_registration(transport: str = 'grpc', request_type=prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest): - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_prediction_api_key_registration), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_prediction_api_key_registration(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_prediction_api_key_registration_from_dict(): - test_delete_prediction_api_key_registration(request_type=dict) - - -def test_delete_prediction_api_key_registration_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionApiKeyRegistryClient( - credentials=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_prediction_api_key_registration), - '__call__') as call: - client.delete_prediction_api_key_registration() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() - - -@pytest.mark.asyncio -async def test_delete_prediction_api_key_registration_async(transport: str = 'grpc_asyncio', request_type=prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest): - client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_prediction_api_key_registration), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_prediction_api_key_registration(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_prediction_api_key_registration_async_from_dict(): - await test_delete_prediction_api_key_registration_async(request_type=dict) - - -def test_delete_prediction_api_key_registration_field_headers(): - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_prediction_api_key_registration), - '__call__') as call: - call.return_value = None - client.delete_prediction_api_key_registration(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_prediction_api_key_registration_field_headers_async(): - client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_prediction_api_key_registration), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_prediction_api_key_registration(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_prediction_api_key_registration_flattened(): - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_prediction_api_key_registration), - '__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_prediction_api_key_registration( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -def test_delete_prediction_api_key_registration_flattened_error(): - client = PredictionApiKeyRegistryClient( - credentials=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_prediction_api_key_registration( - prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_prediction_api_key_registration_flattened_async(): - client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_prediction_api_key_registration), - '__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_prediction_api_key_registration( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_delete_prediction_api_key_registration_flattened_error_async(): - client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_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_prediction_api_key_registration( - prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.PredictionApiKeyRegistryGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.PredictionApiKeyRegistryGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionApiKeyRegistryClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.PredictionApiKeyRegistryGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionApiKeyRegistryClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.PredictionApiKeyRegistryGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = PredictionApiKeyRegistryClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.PredictionApiKeyRegistryGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.PredictionApiKeyRegistryGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.PredictionApiKeyRegistryGrpcTransport, - transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.PredictionApiKeyRegistryGrpcTransport, - ) - -def test_prediction_api_key_registry_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.PredictionApiKeyRegistryTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_prediction_api_key_registry_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry.transports.PredictionApiKeyRegistryTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.PredictionApiKeyRegistryTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_prediction_api_key_registration', - 'list_prediction_api_key_registrations', - 'delete_prediction_api_key_registration', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_prediction_api_key_registry_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.recommendationengine_v1beta1.services.prediction_api_key_registry.transports.PredictionApiKeyRegistryTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PredictionApiKeyRegistryTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_prediction_api_key_registry_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry.transports.PredictionApiKeyRegistryTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PredictionApiKeyRegistryTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - ), - quota_project_id="octopus", - ) - - -def test_prediction_api_key_registry_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.recommendationengine_v1beta1.services.prediction_api_key_registry.transports.PredictionApiKeyRegistryTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PredictionApiKeyRegistryTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_prediction_api_key_registry_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) - PredictionApiKeyRegistryClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_prediction_api_key_registry_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - PredictionApiKeyRegistryClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.PredictionApiKeyRegistryGrpcTransport, - transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_prediction_api_key_registry_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.PredictionApiKeyRegistryGrpcTransport, - transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_prediction_api_key_registry_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.PredictionApiKeyRegistryGrpcTransport, grpc_helpers), - (transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_prediction_api_key_registry_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( - "recommendationengine.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="recommendationengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.PredictionApiKeyRegistryGrpcTransport, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport]) -def test_prediction_api_key_registry_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_prediction_api_key_registry_host_no_port(): - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='recommendationengine.googleapis.com'), - ) - assert client.transport._host == 'recommendationengine.googleapis.com:443' - - -def test_prediction_api_key_registry_host_with_port(): - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='recommendationengine.googleapis.com:8000'), - ) - assert client.transport._host == 'recommendationengine.googleapis.com:8000' - -def test_prediction_api_key_registry_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PredictionApiKeyRegistryGrpcTransport( - 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_prediction_api_key_registry_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PredictionApiKeyRegistryGrpcAsyncIOTransport( - 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.PredictionApiKeyRegistryGrpcTransport, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport]) -def test_prediction_api_key_registry_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.PredictionApiKeyRegistryGrpcTransport, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport]) -def test_prediction_api_key_registry_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_event_store_path(): - project = "squid" - location = "clam" - catalog = "whelk" - event_store = "octopus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}".format(project=project, location=location, catalog=catalog, event_store=event_store, ) - actual = PredictionApiKeyRegistryClient.event_store_path(project, location, catalog, event_store) - assert expected == actual - - -def test_parse_event_store_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "catalog": "cuttlefish", - "event_store": "mussel", - } - path = PredictionApiKeyRegistryClient.event_store_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionApiKeyRegistryClient.parse_event_store_path(path) - assert expected == actual - -def test_prediction_api_key_registration_path(): - project = "winkle" - location = "nautilus" - catalog = "scallop" - event_store = "abalone" - prediction_api_key_registration = "squid" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}/predictionApiKeyRegistrations/{prediction_api_key_registration}".format(project=project, location=location, catalog=catalog, event_store=event_store, prediction_api_key_registration=prediction_api_key_registration, ) - actual = PredictionApiKeyRegistryClient.prediction_api_key_registration_path(project, location, catalog, event_store, prediction_api_key_registration) - assert expected == actual - - -def test_parse_prediction_api_key_registration_path(): - expected = { - "project": "clam", - "location": "whelk", - "catalog": "octopus", - "event_store": "oyster", - "prediction_api_key_registration": "nudibranch", - } - path = PredictionApiKeyRegistryClient.prediction_api_key_registration_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionApiKeyRegistryClient.parse_prediction_api_key_registration_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = PredictionApiKeyRegistryClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = PredictionApiKeyRegistryClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionApiKeyRegistryClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = PredictionApiKeyRegistryClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = PredictionApiKeyRegistryClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionApiKeyRegistryClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = PredictionApiKeyRegistryClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = PredictionApiKeyRegistryClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionApiKeyRegistryClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = PredictionApiKeyRegistryClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = PredictionApiKeyRegistryClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionApiKeyRegistryClient.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 = PredictionApiKeyRegistryClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = PredictionApiKeyRegistryClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionApiKeyRegistryClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.PredictionApiKeyRegistryTransport, '_prep_wrapped_messages') as prep: - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.PredictionApiKeyRegistryTransport, '_prep_wrapped_messages') as prep: - transport_class = PredictionApiKeyRegistryClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py b/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py deleted file mode 100644 index b5583b15..00000000 --- a/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py +++ /dev/null @@ -1,1377 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.recommendationengine_v1beta1.services.prediction_service import PredictionServiceAsyncClient -from google.cloud.recommendationengine_v1beta1.services.prediction_service import PredictionServiceClient -from google.cloud.recommendationengine_v1beta1.services.prediction_service import pagers -from google.cloud.recommendationengine_v1beta1.services.prediction_service import transports -from google.cloud.recommendationengine_v1beta1.services.prediction_service.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.recommendationengine_v1beta1.types import catalog -from google.cloud.recommendationengine_v1beta1.types import common -from google.cloud.recommendationengine_v1beta1.types import prediction_service -from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event -from google.oauth2 import service_account -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert PredictionServiceClient._get_default_mtls_endpoint(None) is None - assert PredictionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert PredictionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - PredictionServiceClient, - PredictionServiceAsyncClient, -]) -def test_prediction_service_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'recommendationengine.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - PredictionServiceClient, - PredictionServiceAsyncClient, -]) -def test_prediction_service_client_service_account_always_use_jwt(client_class): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - client = client_class(credentials=creds) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.PredictionServiceGrpcTransport, "grpc"), - (transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_prediction_service_client_service_account_always_use_jwt_true(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) - - -@pytest.mark.parametrize("client_class", [ - PredictionServiceClient, - PredictionServiceAsyncClient, -]) -def test_prediction_service_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'recommendationengine.googleapis.com:443' - - -def test_prediction_service_client_get_transport_class(): - transport = PredictionServiceClient.get_transport_class() - available_transports = [ - transports.PredictionServiceGrpcTransport, - ] - assert transport in available_transports - - transport = PredictionServiceClient.get_transport_class("grpc") - assert transport == transports.PredictionServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -def test_prediction_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(PredictionServiceClient, '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(PredictionServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "true"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", "false"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(PredictionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceClient)) -@mock.patch.object(PredictionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_prediction_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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_prediction_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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), - (PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_prediction_service_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_prediction_service_client_client_options_from_dict(): - with mock.patch('google.cloud.recommendationengine_v1beta1.services.prediction_service.transports.PredictionServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = PredictionServiceClient( - 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, - ) - - -def test_predict(transport: str = 'grpc', request_type=prediction_service.PredictRequest): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = prediction_service.PredictResponse( - recommendation_token='recommendation_token_value', - items_missing_in_catalog=['items_missing_in_catalog_value'], - dry_run=True, - next_page_token='next_page_token_value', - ) - response = client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.PredictPager) - assert response.recommendation_token == 'recommendation_token_value' - assert response.items_missing_in_catalog == ['items_missing_in_catalog_value'] - assert response.dry_run is True - assert response.next_page_token == 'next_page_token_value' - - -def test_predict_from_dict(): - test_predict(request_type=dict) - - -def test_predict_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - client.predict() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - -@pytest.mark.asyncio -async def test_predict_async(transport: str = 'grpc_asyncio', request_type=prediction_service.PredictRequest): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse( - recommendation_token='recommendation_token_value', - items_missing_in_catalog=['items_missing_in_catalog_value'], - dry_run=True, - next_page_token='next_page_token_value', - )) - response = await client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.PredictAsyncPager) - assert response.recommendation_token == 'recommendation_token_value' - assert response.items_missing_in_catalog == ['items_missing_in_catalog_value'] - assert response.dry_run is True - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_predict_async_from_dict(): - await test_predict_async(request_type=dict) - - -def test_predict_field_headers(): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = prediction_service.PredictRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - call.return_value = prediction_service.PredictResponse() - client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_predict_field_headers_async(): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = prediction_service.PredictRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse()) - await client.predict(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_predict_flattened(): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = prediction_service.PredictResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.predict( - name='name_value', - user_event=gcr_user_event.UserEvent(event_type='event_type_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - assert args[0].user_event == gcr_user_event.UserEvent(event_type='event_type_value') - - -def test_predict_flattened_error(): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.predict( - prediction_service.PredictRequest(), - name='name_value', - user_event=gcr_user_event.UserEvent(event_type='event_type_value'), - ) - - -@pytest.mark.asyncio -async def test_predict_flattened_async(): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = prediction_service.PredictResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.predict( - name='name_value', - user_event=gcr_user_event.UserEvent(event_type='event_type_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - assert args[0].user_event == gcr_user_event.UserEvent(event_type='event_type_value') - - -@pytest.mark.asyncio -async def test_predict_flattened_error_async(): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.predict( - prediction_service.PredictRequest(), - name='name_value', - user_event=gcr_user_event.UserEvent(event_type='event_type_value'), - ) - - -def test_predict_pager(): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - prediction_service.PredictResponse( - results=[ - prediction_service.PredictResponse.PredictionResult(), - prediction_service.PredictResponse.PredictionResult(), - prediction_service.PredictResponse.PredictionResult(), - ], - next_page_token='abc', - ), - prediction_service.PredictResponse( - results=[], - next_page_token='def', - ), - prediction_service.PredictResponse( - results=[ - prediction_service.PredictResponse.PredictionResult(), - ], - next_page_token='ghi', - ), - prediction_service.PredictResponse( - results=[ - prediction_service.PredictResponse.PredictionResult(), - prediction_service.PredictResponse.PredictionResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('name', ''), - )), - ) - pager = client.predict(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, prediction_service.PredictResponse.PredictionResult) - for i in results) - -def test_predict_pages(): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - prediction_service.PredictResponse( - results=[ - prediction_service.PredictResponse.PredictionResult(), - prediction_service.PredictResponse.PredictionResult(), - prediction_service.PredictResponse.PredictionResult(), - ], - next_page_token='abc', - ), - prediction_service.PredictResponse( - results=[], - next_page_token='def', - ), - prediction_service.PredictResponse( - results=[ - prediction_service.PredictResponse.PredictionResult(), - ], - next_page_token='ghi', - ), - prediction_service.PredictResponse( - results=[ - prediction_service.PredictResponse.PredictionResult(), - prediction_service.PredictResponse.PredictionResult(), - ], - ), - RuntimeError, - ) - pages = list(client.predict(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_predict_async_pager(): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - prediction_service.PredictResponse( - results=[ - prediction_service.PredictResponse.PredictionResult(), - prediction_service.PredictResponse.PredictionResult(), - prediction_service.PredictResponse.PredictionResult(), - ], - next_page_token='abc', - ), - prediction_service.PredictResponse( - results=[], - next_page_token='def', - ), - prediction_service.PredictResponse( - results=[ - prediction_service.PredictResponse.PredictionResult(), - ], - next_page_token='ghi', - ), - prediction_service.PredictResponse( - results=[ - prediction_service.PredictResponse.PredictionResult(), - prediction_service.PredictResponse.PredictionResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.predict(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, prediction_service.PredictResponse.PredictionResult) - for i in responses) - -@pytest.mark.asyncio -async def test_predict_async_pages(): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.predict), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - prediction_service.PredictResponse( - results=[ - prediction_service.PredictResponse.PredictionResult(), - prediction_service.PredictResponse.PredictionResult(), - prediction_service.PredictResponse.PredictionResult(), - ], - next_page_token='abc', - ), - prediction_service.PredictResponse( - results=[], - next_page_token='def', - ), - prediction_service.PredictResponse( - results=[ - prediction_service.PredictResponse.PredictionResult(), - ], - next_page_token='ghi', - ), - prediction_service.PredictResponse( - results=[ - prediction_service.PredictResponse.PredictionResult(), - prediction_service.PredictResponse.PredictionResult(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.predict(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = PredictionServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.PredictionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.PredictionServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.PredictionServiceGrpcTransport, - ) - -def test_prediction_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.PredictionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_prediction_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.recommendationengine_v1beta1.services.prediction_service.transports.PredictionServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.PredictionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'predict', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_prediction_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.recommendationengine_v1beta1.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PredictionServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_prediction_service_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.recommendationengine_v1beta1.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PredictionServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - ), - quota_project_id="octopus", - ) - - -def test_prediction_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.recommendationengine_v1beta1.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PredictionServiceTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_prediction_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) - PredictionServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_prediction_service_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - PredictionServiceClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_prediction_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.PredictionServiceGrpcTransport, - transports.PredictionServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_prediction_service_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.PredictionServiceGrpcTransport, grpc_helpers), - (transports.PredictionServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_prediction_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( - "recommendationengine.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="recommendationengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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_prediction_service_host_no_port(): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='recommendationengine.googleapis.com'), - ) - assert client.transport._host == 'recommendationengine.googleapis.com:443' - - -def test_prediction_service_host_with_port(): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='recommendationengine.googleapis.com:8000'), - ) - assert client.transport._host == 'recommendationengine.googleapis.com:8000' - -def test_prediction_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PredictionServiceGrpcTransport( - 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_prediction_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PredictionServiceGrpcAsyncIOTransport( - 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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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.PredictionServiceGrpcTransport, transports.PredictionServiceGrpcAsyncIOTransport]) -def test_prediction_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_placement_path(): - project = "squid" - location = "clam" - catalog = "whelk" - event_store = "octopus" - placement = "oyster" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}/placements/{placement}".format(project=project, location=location, catalog=catalog, event_store=event_store, placement=placement, ) - actual = PredictionServiceClient.placement_path(project, location, catalog, event_store, placement) - assert expected == actual - - -def test_parse_placement_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "catalog": "mussel", - "event_store": "winkle", - "placement": "nautilus", - } - path = PredictionServiceClient.placement_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_placement_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = PredictionServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = PredictionServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = PredictionServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = PredictionServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = PredictionServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = PredictionServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = PredictionServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = PredictionServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.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 = PredictionServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = PredictionServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = PredictionServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.PredictionServiceTransport, '_prep_wrapped_messages') as prep: - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.PredictionServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = PredictionServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_user_event_service.py b/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_user_event_service.py deleted file mode 100644 index 411b1828..00000000 --- a/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_user_event_service.py +++ /dev/null @@ -1,2394 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.recommendationengine_v1beta1.services.user_event_service import UserEventServiceAsyncClient -from google.cloud.recommendationengine_v1beta1.services.user_event_service import UserEventServiceClient -from google.cloud.recommendationengine_v1beta1.services.user_event_service import pagers -from google.cloud.recommendationengine_v1beta1.services.user_event_service import transports -from google.cloud.recommendationengine_v1beta1.services.user_event_service.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.recommendationengine_v1beta1.types import catalog -from google.cloud.recommendationengine_v1beta1.types import common -from google.cloud.recommendationengine_v1beta1.types import import_ -from google.cloud.recommendationengine_v1beta1.types import user_event -from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event -from google.cloud.recommendationengine_v1beta1.types import user_event_service -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert UserEventServiceClient._get_default_mtls_endpoint(None) is None - assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - UserEventServiceClient, - UserEventServiceAsyncClient, -]) -def test_user_event_service_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'recommendationengine.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - UserEventServiceClient, - UserEventServiceAsyncClient, -]) -def test_user_event_service_client_service_account_always_use_jwt(client_class): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - client = client_class(credentials=creds) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.UserEventServiceGrpcTransport, "grpc"), - (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_user_event_service_client_service_account_always_use_jwt_true(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) - - -@pytest.mark.parametrize("client_class", [ - UserEventServiceClient, - UserEventServiceAsyncClient, -]) -def test_user_event_service_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'recommendationengine.googleapis.com:443' - - -def test_user_event_service_client_get_transport_class(): - transport = UserEventServiceClient.get_transport_class() - available_transports = [ - transports.UserEventServiceGrpcTransport, - ] - assert transport in available_transports - - transport = UserEventServiceClient.get_transport_class("grpc") - assert transport == transports.UserEventServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -def test_user_event_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(UserEventServiceClient, '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(UserEventServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_user_event_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) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_user_event_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) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_user_event_service_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_user_event_service_client_client_options_from_dict(): - with mock.patch('google.cloud.recommendationengine_v1beta1.services.user_event_service.transports.UserEventServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = UserEventServiceClient( - 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, - ) - - -def test_write_user_event(transport: str = 'grpc', request_type=user_event_service.WriteUserEventRequest): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_user_event.UserEvent( - event_type='event_type_value', - event_source=gcr_user_event.UserEvent.EventSource.AUTOML, - ) - response = client.write_user_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] == user_event_service.WriteUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.event_source == gcr_user_event.UserEvent.EventSource.AUTOML - - -def test_write_user_event_from_dict(): - test_write_user_event(request_type=dict) - - -def test_write_user_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 = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - client.write_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - -@pytest.mark.asyncio -async def test_write_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.WriteUserEventRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcr_user_event.UserEvent( - event_type='event_type_value', - event_source=gcr_user_event.UserEvent.EventSource.AUTOML, - )) - response = await client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.event_source == gcr_user_event.UserEvent.EventSource.AUTOML - - -@pytest.mark.asyncio -async def test_write_user_event_async_from_dict(): - await test_write_user_event_async(request_type=dict) - - -def test_write_user_event_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.WriteUserEventRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - call.return_value = gcr_user_event.UserEvent() - client.write_user_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_write_user_event_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.WriteUserEventRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_user_event.UserEvent()) - await client.write_user_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_write_user_event_flattened(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_user_event.UserEvent() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.write_user_event( - parent='parent_value', - user_event=gcr_user_event.UserEvent(event_type='event_type_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].user_event == gcr_user_event.UserEvent(event_type='event_type_value') - - -def test_write_user_event_flattened_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.write_user_event( - user_event_service.WriteUserEventRequest(), - parent='parent_value', - user_event=gcr_user_event.UserEvent(event_type='event_type_value'), - ) - - -@pytest.mark.asyncio -async def test_write_user_event_flattened_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcr_user_event.UserEvent() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_user_event.UserEvent()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.write_user_event( - parent='parent_value', - user_event=gcr_user_event.UserEvent(event_type='event_type_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].user_event == gcr_user_event.UserEvent(event_type='event_type_value') - - -@pytest.mark.asyncio -async def test_write_user_event_flattened_error_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.write_user_event( - user_event_service.WriteUserEventRequest(), - parent='parent_value', - user_event=gcr_user_event.UserEvent(event_type='event_type_value'), - ) - - -def test_collect_user_event(transport: str = 'grpc', request_type=user_event_service.CollectUserEventRequest): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - ) - response = client.collect_user_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] == user_event_service.CollectUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -def test_collect_user_event_from_dict(): - test_collect_user_event(request_type=dict) - - -def test_collect_user_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 = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - client.collect_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - -@pytest.mark.asyncio -async def test_collect_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.CollectUserEventRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - )) - response = await client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -@pytest.mark.asyncio -async def test_collect_user_event_async_from_dict(): - await test_collect_user_event_async(request_type=dict) - - -def test_collect_user_event_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.CollectUserEventRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - call.return_value = httpbody_pb2.HttpBody() - client.collect_user_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_collect_user_event_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.CollectUserEventRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) - await client.collect_user_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_collect_user_event_flattened(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = httpbody_pb2.HttpBody() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.collect_user_event( - parent='parent_value', - user_event='user_event_value', - uri='uri_value', - ets=332, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].user_event == 'user_event_value' - assert args[0].uri == 'uri_value' - assert args[0].ets == 332 - - -def test_collect_user_event_flattened_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.collect_user_event( - user_event_service.CollectUserEventRequest(), - parent='parent_value', - user_event='user_event_value', - uri='uri_value', - ets=332, - ) - - -@pytest.mark.asyncio -async def test_collect_user_event_flattened_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = httpbody_pb2.HttpBody() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.collect_user_event( - parent='parent_value', - user_event='user_event_value', - uri='uri_value', - ets=332, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].user_event == 'user_event_value' - assert args[0].uri == 'uri_value' - assert args[0].ets == 332 - - -@pytest.mark.asyncio -async def test_collect_user_event_flattened_error_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.collect_user_event( - user_event_service.CollectUserEventRequest(), - parent='parent_value', - user_event='user_event_value', - uri='uri_value', - ets=332, - ) - - -def test_list_user_events(transport: str = 'grpc', request_type=user_event_service.ListUserEventsRequest): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = user_event_service.ListUserEventsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_user_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] == user_event_service.ListUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUserEventsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_user_events_from_dict(): - test_list_user_events(request_type=dict) - - -def test_list_user_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 = UserEventServiceClient( - credentials=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_user_events), - '__call__') as call: - client.list_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.ListUserEventsRequest() - - -@pytest.mark.asyncio -async def test_list_user_events_async(transport: str = 'grpc_asyncio', request_type=user_event_service.ListUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event_service.ListUserEventsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.ListUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUserEventsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_user_events_async_from_dict(): - await test_list_user_events_async(request_type=dict) - - -def test_list_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.ListUserEventsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_events), - '__call__') as call: - call.return_value = user_event_service.ListUserEventsResponse() - client.list_user_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_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.ListUserEventsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event_service.ListUserEventsResponse()) - await client.list_user_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_user_events_flattened(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = user_event_service.ListUserEventsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_user_events( - parent='parent_value', - filter='filter_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].filter == 'filter_value' - - -def test_list_user_events_flattened_error(): - client = UserEventServiceClient( - credentials=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_user_events( - user_event_service.ListUserEventsRequest(), - parent='parent_value', - filter='filter_value', - ) - - -@pytest.mark.asyncio -async def test_list_user_events_flattened_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = user_event_service.ListUserEventsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event_service.ListUserEventsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_user_events( - parent='parent_value', - filter='filter_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].filter == 'filter_value' - - -@pytest.mark.asyncio -async def test_list_user_events_flattened_error_async(): - client = UserEventServiceAsyncClient( - credentials=ga_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_user_events( - user_event_service.ListUserEventsRequest(), - parent='parent_value', - filter='filter_value', - ) - - -def test_list_user_events_pager(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_events), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - user_event_service.ListUserEventsResponse( - user_events=[ - user_event.UserEvent(), - user_event.UserEvent(), - user_event.UserEvent(), - ], - next_page_token='abc', - ), - user_event_service.ListUserEventsResponse( - user_events=[], - next_page_token='def', - ), - user_event_service.ListUserEventsResponse( - user_events=[ - user_event.UserEvent(), - ], - next_page_token='ghi', - ), - user_event_service.ListUserEventsResponse( - user_events=[ - user_event.UserEvent(), - user_event.UserEvent(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_user_events(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, user_event.UserEvent) - for i in results) - -def test_list_user_events_pages(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_events), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - user_event_service.ListUserEventsResponse( - user_events=[ - user_event.UserEvent(), - user_event.UserEvent(), - user_event.UserEvent(), - ], - next_page_token='abc', - ), - user_event_service.ListUserEventsResponse( - user_events=[], - next_page_token='def', - ), - user_event_service.ListUserEventsResponse( - user_events=[ - user_event.UserEvent(), - ], - next_page_token='ghi', - ), - user_event_service.ListUserEventsResponse( - user_events=[ - user_event.UserEvent(), - user_event.UserEvent(), - ], - ), - RuntimeError, - ) - pages = list(client.list_user_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_user_events_async_pager(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_events), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - user_event_service.ListUserEventsResponse( - user_events=[ - user_event.UserEvent(), - user_event.UserEvent(), - user_event.UserEvent(), - ], - next_page_token='abc', - ), - user_event_service.ListUserEventsResponse( - user_events=[], - next_page_token='def', - ), - user_event_service.ListUserEventsResponse( - user_events=[ - user_event.UserEvent(), - ], - next_page_token='ghi', - ), - user_event_service.ListUserEventsResponse( - user_events=[ - user_event.UserEvent(), - user_event.UserEvent(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_user_events(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, user_event.UserEvent) - for i in responses) - -@pytest.mark.asyncio -async def test_list_user_events_async_pages(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_events), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - user_event_service.ListUserEventsResponse( - user_events=[ - user_event.UserEvent(), - user_event.UserEvent(), - user_event.UserEvent(), - ], - next_page_token='abc', - ), - user_event_service.ListUserEventsResponse( - user_events=[], - next_page_token='def', - ), - user_event_service.ListUserEventsResponse( - user_events=[ - user_event.UserEvent(), - ], - next_page_token='ghi', - ), - user_event_service.ListUserEventsResponse( - user_events=[ - user_event.UserEvent(), - user_event.UserEvent(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_user_events(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_purge_user_events(transport: str = 'grpc', request_type=user_event_service.PurgeUserEventsRequest): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.purge_user_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] == user_event_service.PurgeUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_purge_user_events_from_dict(): - test_purge_user_events(request_type=dict) - - -def test_purge_user_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 = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - client.purge_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.PurgeUserEventsRequest() - - -@pytest.mark.asyncio -async def test_purge_user_events_async(transport: str = 'grpc_asyncio', request_type=user_event_service.PurgeUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__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.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.PurgeUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_purge_user_events_async_from_dict(): - await test_purge_user_events_async(request_type=dict) - - -def test_purge_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.PurgeUserEventsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.purge_user_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_purge_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.PurgeUserEventsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.purge_user_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_purge_user_events_flattened(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__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.purge_user_events( - parent='parent_value', - filter='filter_value', - force=True, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].filter == 'filter_value' - assert args[0].force == True - - -def test_purge_user_events_flattened_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.purge_user_events( - user_event_service.PurgeUserEventsRequest(), - parent='parent_value', - filter='filter_value', - force=True, - ) - - -@pytest.mark.asyncio -async def test_purge_user_events_flattened_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__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.purge_user_events( - parent='parent_value', - filter='filter_value', - force=True, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].filter == 'filter_value' - assert args[0].force == True - - -@pytest.mark.asyncio -async def test_purge_user_events_flattened_error_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.purge_user_events( - user_event_service.PurgeUserEventsRequest(), - parent='parent_value', - filter='filter_value', - force=True, - ) - - -def test_import_user_events(transport: str = 'grpc', request_type=import_.ImportUserEventsRequest): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_user_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] == import_.ImportUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_user_events_from_dict(): - test_import_user_events(request_type=dict) - - -def test_import_user_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 = UserEventServiceClient( - credentials=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_user_events), - '__call__') as call: - client.import_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_.ImportUserEventsRequest() - - -@pytest.mark.asyncio -async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_.ImportUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_user_events), - '__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_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_.ImportUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_user_events_async_from_dict(): - await test_import_user_events_async(request_type=dict) - - -def test_import_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_.ImportUserEventsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_user_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_import_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_.ImportUserEventsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_user_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_import_user_events_flattened(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__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.import_user_events( - parent='parent_value', - request_id='request_id_value', - input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), - errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].request_id == 'request_id_value' - assert args[0].input_config == import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])) - assert args[0].errors_config == import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value') - - -def test_import_user_events_flattened_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.import_user_events( - import_.ImportUserEventsRequest(), - parent='parent_value', - request_id='request_id_value', - input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), - errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), - ) - - -@pytest.mark.asyncio -async def test_import_user_events_flattened_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__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.import_user_events( - parent='parent_value', - request_id='request_id_value', - input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), - errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].request_id == 'request_id_value' - assert args[0].input_config == import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])) - assert args[0].errors_config == import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value') - - -@pytest.mark.asyncio -async def test_import_user_events_flattened_error_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.import_user_events( - import_.ImportUserEventsRequest(), - parent='parent_value', - request_id='request_id_value', - input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), - errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = UserEventServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.UserEventServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.UserEventServiceGrpcTransport, - ) - -def test_user_event_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.UserEventServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_user_event_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.recommendationengine_v1beta1.services.user_event_service.transports.UserEventServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.UserEventServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'write_user_event', - 'collect_user_event', - 'list_user_events', - 'purge_user_events', - 'import_user_events', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -def test_user_event_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.recommendationengine_v1beta1.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_user_event_service_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.recommendationengine_v1beta1.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - ), - quota_project_id="octopus", - ) - - -def test_user_event_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.recommendationengine_v1beta1.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_user_event_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) - UserEventServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_user_event_service_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - UserEventServiceClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_user_event_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.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_user_event_service_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.UserEventServiceGrpcTransport, grpc_helpers), - (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_user_event_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( - "recommendationengine.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="recommendationengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_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_user_event_service_host_no_port(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='recommendationengine.googleapis.com'), - ) - assert client.transport._host == 'recommendationengine.googleapis.com:443' - - -def test_user_event_service_host_with_port(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='recommendationengine.googleapis.com:8000'), - ) - assert client.transport._host == 'recommendationengine.googleapis.com:8000' - -def test_user_event_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserEventServiceGrpcTransport( - 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_user_event_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserEventServiceGrpcAsyncIOTransport( - 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.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_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.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_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_user_event_service_grpc_lro_client(): - client = UserEventServiceClient( - 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_user_event_service_grpc_lro_async_client(): - client = UserEventServiceAsyncClient( - 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_event_store_path(): - project = "squid" - location = "clam" - catalog = "whelk" - event_store = "octopus" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}".format(project=project, location=location, catalog=catalog, event_store=event_store, ) - actual = UserEventServiceClient.event_store_path(project, location, catalog, event_store) - assert expected == actual - - -def test_parse_event_store_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "catalog": "cuttlefish", - "event_store": "mussel", - } - path = UserEventServiceClient.event_store_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_event_store_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = UserEventServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = UserEventServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = UserEventServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = UserEventServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = UserEventServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = UserEventServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = UserEventServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = UserEventServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.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 = UserEventServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = UserEventServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = UserEventServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/recommendationengine_v1beta1/test_catalog_service.py b/tests/unit/gapic/recommendationengine_v1beta1/test_catalog_service.py index 6012e9ea..a247fd50 100644 --- a/tests/unit/gapic/recommendationengine_v1beta1/test_catalog_service.py +++ b/tests/unit/gapic/recommendationengine_v1beta1/test_catalog_service.py @@ -143,7 +143,25 @@ def test_catalog_service_client_service_account_always_use_jwt(client_class): ) as use_jwt: creds = service_account.Credentials(None, None, None) client = client_class(credentials=creds) - use_jwt.assert_called_with(True) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.CatalogServiceGrpcTransport, "grpc"), + (transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_catalog_service_client_service_account_always_use_jwt_true( + 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) @pytest.mark.parametrize( @@ -2369,7 +2387,7 @@ def test_catalog_service_grpc_transport_client_cert_source_for_mtls(transport_cl "squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_channel_creds, quota_project_id=None, options=[ @@ -2478,7 +2496,7 @@ def test_catalog_service_transport_channel_mtls_with_client_cert_source( "mtls.squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ @@ -2525,7 +2543,7 @@ def test_catalog_service_transport_channel_mtls_with_adc(transport_class): "mtls.squid.clam.whelk:443", credentials=mock_cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ diff --git a/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_api_key_registry.py b/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_api_key_registry.py index 6497d77b..52d55c78 100644 --- a/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_api_key_registry.py +++ b/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_api_key_registry.py @@ -142,7 +142,25 @@ def test_prediction_api_key_registry_client_service_account_always_use_jwt( ) as use_jwt: creds = service_account.Credentials(None, None, None) client = client_class(credentials=creds) - use_jwt.assert_called_with(True) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.PredictionApiKeyRegistryGrpcTransport, "grpc"), + (transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_prediction_api_key_registry_client_service_account_always_use_jwt_true( + 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) @pytest.mark.parametrize( @@ -1765,7 +1783,7 @@ def test_prediction_api_key_registry_grpc_transport_client_cert_source_for_mtls( "squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_channel_creds, quota_project_id=None, options=[ @@ -1874,7 +1892,7 @@ def test_prediction_api_key_registry_transport_channel_mtls_with_client_cert_sou "mtls.squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ @@ -1921,7 +1939,7 @@ def test_prediction_api_key_registry_transport_channel_mtls_with_adc(transport_c "mtls.squid.clam.whelk:443", credentials=mock_cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ diff --git a/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py b/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py index 8d5a8919..8bd08dfa 100644 --- a/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py +++ b/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py @@ -139,7 +139,25 @@ def test_prediction_service_client_service_account_always_use_jwt(client_class): ) as use_jwt: creds = service_account.Credentials(None, None, None) client = client_class(credentials=creds) - use_jwt.assert_called_with(True) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.PredictionServiceGrpcTransport, "grpc"), + (transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_prediction_service_client_service_account_always_use_jwt_true( + 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) @pytest.mark.parametrize( @@ -1168,7 +1186,7 @@ def test_prediction_service_grpc_transport_client_cert_source_for_mtls(transport "squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_channel_creds, quota_project_id=None, options=[ @@ -1277,7 +1295,7 @@ def test_prediction_service_transport_channel_mtls_with_client_cert_source( "mtls.squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ @@ -1324,7 +1342,7 @@ def test_prediction_service_transport_channel_mtls_with_adc(transport_class): "mtls.squid.clam.whelk:443", credentials=mock_cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ diff --git a/tests/unit/gapic/recommendationengine_v1beta1/test_user_event_service.py b/tests/unit/gapic/recommendationengine_v1beta1/test_user_event_service.py index b4cdf4bc..d69ec5cd 100644 --- a/tests/unit/gapic/recommendationengine_v1beta1/test_user_event_service.py +++ b/tests/unit/gapic/recommendationengine_v1beta1/test_user_event_service.py @@ -146,7 +146,25 @@ def test_user_event_service_client_service_account_always_use_jwt(client_class): ) as use_jwt: creds = service_account.Credentials(None, None, None) client = client_class(credentials=creds) - use_jwt.assert_called_with(True) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.UserEventServiceGrpcTransport, "grpc"), + (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_user_event_service_client_service_account_always_use_jwt_true( + 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) @pytest.mark.parametrize( @@ -2122,7 +2140,7 @@ def test_user_event_service_grpc_transport_client_cert_source_for_mtls(transport "squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_channel_creds, quota_project_id=None, options=[ @@ -2231,7 +2249,7 @@ def test_user_event_service_transport_channel_mtls_with_client_cert_source( "mtls.squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ @@ -2278,7 +2296,7 @@ def test_user_event_service_transport_channel_mtls_with_adc(transport_class): "mtls.squid.clam.whelk:443", credentials=mock_cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[