diff --git a/owl-bot-staging/v2/.coveragerc b/owl-bot-staging/v2/.coveragerc new file mode 100644 index 000000000..09666453e --- /dev/null +++ b/owl-bot-staging/v2/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/dialogflow/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v2/MANIFEST.in b/owl-bot-staging/v2/MANIFEST.in new file mode 100644 index 000000000..e6fb0b1cd --- /dev/null +++ b/owl-bot-staging/v2/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/dialogflow *.py +recursive-include google/cloud/dialogflow_v2 *.py diff --git a/owl-bot-staging/v2/README.rst b/owl-bot-staging/v2/README.rst new file mode 100644 index 000000000..6a2fa7289 --- /dev/null +++ b/owl-bot-staging/v2/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Dialogflow 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 Dialogflow API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v2/docs/conf.py b/owl-bot-staging/v2/docs/conf.py new file mode 100644 index 000000000..8b2599a7e --- /dev/null +++ b/owl-bot-staging/v2/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-dialogflow 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-dialogflow" +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-dialogflow-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-dialogflow.tex", + u"google-cloud-dialogflow 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-dialogflow", + u"Google Cloud Dialogflow 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-dialogflow", + u"google-cloud-dialogflow Documentation", + author, + "google-cloud-dialogflow", + "GAPIC library for Google Cloud Dialogflow API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/agents.rst b/owl-bot-staging/v2/docs/dialogflow_v2/agents.rst new file mode 100644 index 000000000..8661ecd44 --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/agents.rst @@ -0,0 +1,10 @@ +Agents +------------------------ + +.. automodule:: google.cloud.dialogflow_v2.services.agents + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2.services.agents.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/answer_records.rst b/owl-bot-staging/v2/docs/dialogflow_v2/answer_records.rst new file mode 100644 index 000000000..20345f618 --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/answer_records.rst @@ -0,0 +1,10 @@ +AnswerRecords +------------------------------- + +.. automodule:: google.cloud.dialogflow_v2.services.answer_records + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2.services.answer_records.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/contexts.rst b/owl-bot-staging/v2/docs/dialogflow_v2/contexts.rst new file mode 100644 index 000000000..ab27d7b1e --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/contexts.rst @@ -0,0 +1,10 @@ +Contexts +-------------------------- + +.. automodule:: google.cloud.dialogflow_v2.services.contexts + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2.services.contexts.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/conversation_profiles.rst b/owl-bot-staging/v2/docs/dialogflow_v2/conversation_profiles.rst new file mode 100644 index 000000000..e5c4cda45 --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/conversation_profiles.rst @@ -0,0 +1,10 @@ +ConversationProfiles +-------------------------------------- + +.. automodule:: google.cloud.dialogflow_v2.services.conversation_profiles + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2.services.conversation_profiles.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/conversations.rst b/owl-bot-staging/v2/docs/dialogflow_v2/conversations.rst new file mode 100644 index 000000000..a288e3783 --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/conversations.rst @@ -0,0 +1,10 @@ +Conversations +------------------------------- + +.. automodule:: google.cloud.dialogflow_v2.services.conversations + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2.services.conversations.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/documents.rst b/owl-bot-staging/v2/docs/dialogflow_v2/documents.rst new file mode 100644 index 000000000..c95415ace --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/documents.rst @@ -0,0 +1,10 @@ +Documents +--------------------------- + +.. automodule:: google.cloud.dialogflow_v2.services.documents + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2.services.documents.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/entity_types.rst b/owl-bot-staging/v2/docs/dialogflow_v2/entity_types.rst new file mode 100644 index 000000000..82634156b --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/entity_types.rst @@ -0,0 +1,10 @@ +EntityTypes +----------------------------- + +.. automodule:: google.cloud.dialogflow_v2.services.entity_types + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2.services.entity_types.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/environments.rst b/owl-bot-staging/v2/docs/dialogflow_v2/environments.rst new file mode 100644 index 000000000..e0ca6f7f7 --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/environments.rst @@ -0,0 +1,10 @@ +Environments +------------------------------ + +.. automodule:: google.cloud.dialogflow_v2.services.environments + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2.services.environments.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/fulfillments.rst b/owl-bot-staging/v2/docs/dialogflow_v2/fulfillments.rst new file mode 100644 index 000000000..27f77aa3a --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/fulfillments.rst @@ -0,0 +1,6 @@ +Fulfillments +------------------------------ + +.. automodule:: google.cloud.dialogflow_v2.services.fulfillments + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/intents.rst b/owl-bot-staging/v2/docs/dialogflow_v2/intents.rst new file mode 100644 index 000000000..8418cb20d --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/intents.rst @@ -0,0 +1,10 @@ +Intents +------------------------- + +.. automodule:: google.cloud.dialogflow_v2.services.intents + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2.services.intents.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/knowledge_bases.rst b/owl-bot-staging/v2/docs/dialogflow_v2/knowledge_bases.rst new file mode 100644 index 000000000..7440330af --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/knowledge_bases.rst @@ -0,0 +1,10 @@ +KnowledgeBases +-------------------------------- + +.. automodule:: google.cloud.dialogflow_v2.services.knowledge_bases + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2.services.knowledge_bases.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/participants.rst b/owl-bot-staging/v2/docs/dialogflow_v2/participants.rst new file mode 100644 index 000000000..6ce8a2c52 --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/participants.rst @@ -0,0 +1,10 @@ +Participants +------------------------------ + +.. automodule:: google.cloud.dialogflow_v2.services.participants + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2.services.participants.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/services.rst b/owl-bot-staging/v2/docs/dialogflow_v2/services.rst new file mode 100644 index 000000000..8bdbdfe41 --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/services.rst @@ -0,0 +1,20 @@ +Services for Google Cloud Dialogflow v2 API +=========================================== +.. toctree:: + :maxdepth: 2 + + agents + answer_records + contexts + conversation_profiles + conversations + documents + entity_types + environments + fulfillments + intents + knowledge_bases + participants + session_entity_types + sessions + versions diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/session_entity_types.rst b/owl-bot-staging/v2/docs/dialogflow_v2/session_entity_types.rst new file mode 100644 index 000000000..e1d7bd321 --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/session_entity_types.rst @@ -0,0 +1,10 @@ +SessionEntityTypes +------------------------------------ + +.. automodule:: google.cloud.dialogflow_v2.services.session_entity_types + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2.services.session_entity_types.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/sessions.rst b/owl-bot-staging/v2/docs/dialogflow_v2/sessions.rst new file mode 100644 index 000000000..1da650e33 --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/sessions.rst @@ -0,0 +1,6 @@ +Sessions +-------------------------- + +.. automodule:: google.cloud.dialogflow_v2.services.sessions + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/types.rst b/owl-bot-staging/v2/docs/dialogflow_v2/types.rst new file mode 100644 index 000000000..205c4fadd --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Dialogflow v2 API +======================================== + +.. automodule:: google.cloud.dialogflow_v2.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/versions.rst b/owl-bot-staging/v2/docs/dialogflow_v2/versions.rst new file mode 100644 index 000000000..af34a4719 --- /dev/null +++ b/owl-bot-staging/v2/docs/dialogflow_v2/versions.rst @@ -0,0 +1,10 @@ +Versions +-------------------------- + +.. automodule:: google.cloud.dialogflow_v2.services.versions + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2.services.versions.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/index.rst b/owl-bot-staging/v2/docs/index.rst new file mode 100644 index 000000000..79b49743a --- /dev/null +++ b/owl-bot-staging/v2/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + dialogflow_v2/services + dialogflow_v2/types diff --git a/owl-bot-staging/v2/google/cloud/dialogflow/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow/__init__.py new file mode 100644 index 000000000..afe6fc525 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow/__init__.py @@ -0,0 +1,425 @@ +# -*- 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.dialogflow_v2.services.agents.client import AgentsClient +from google.cloud.dialogflow_v2.services.agents.async_client import AgentsAsyncClient +from google.cloud.dialogflow_v2.services.answer_records.client import AnswerRecordsClient +from google.cloud.dialogflow_v2.services.answer_records.async_client import AnswerRecordsAsyncClient +from google.cloud.dialogflow_v2.services.contexts.client import ContextsClient +from google.cloud.dialogflow_v2.services.contexts.async_client import ContextsAsyncClient +from google.cloud.dialogflow_v2.services.conversation_profiles.client import ConversationProfilesClient +from google.cloud.dialogflow_v2.services.conversation_profiles.async_client import ConversationProfilesAsyncClient +from google.cloud.dialogflow_v2.services.conversations.client import ConversationsClient +from google.cloud.dialogflow_v2.services.conversations.async_client import ConversationsAsyncClient +from google.cloud.dialogflow_v2.services.documents.client import DocumentsClient +from google.cloud.dialogflow_v2.services.documents.async_client import DocumentsAsyncClient +from google.cloud.dialogflow_v2.services.entity_types.client import EntityTypesClient +from google.cloud.dialogflow_v2.services.entity_types.async_client import EntityTypesAsyncClient +from google.cloud.dialogflow_v2.services.environments.client import EnvironmentsClient +from google.cloud.dialogflow_v2.services.environments.async_client import EnvironmentsAsyncClient +from google.cloud.dialogflow_v2.services.fulfillments.client import FulfillmentsClient +from google.cloud.dialogflow_v2.services.fulfillments.async_client import FulfillmentsAsyncClient +from google.cloud.dialogflow_v2.services.intents.client import IntentsClient +from google.cloud.dialogflow_v2.services.intents.async_client import IntentsAsyncClient +from google.cloud.dialogflow_v2.services.knowledge_bases.client import KnowledgeBasesClient +from google.cloud.dialogflow_v2.services.knowledge_bases.async_client import KnowledgeBasesAsyncClient +from google.cloud.dialogflow_v2.services.participants.client import ParticipantsClient +from google.cloud.dialogflow_v2.services.participants.async_client import ParticipantsAsyncClient +from google.cloud.dialogflow_v2.services.session_entity_types.client import SessionEntityTypesClient +from google.cloud.dialogflow_v2.services.session_entity_types.async_client import SessionEntityTypesAsyncClient +from google.cloud.dialogflow_v2.services.sessions.client import SessionsClient +from google.cloud.dialogflow_v2.services.sessions.async_client import SessionsAsyncClient +from google.cloud.dialogflow_v2.services.versions.client import VersionsClient +from google.cloud.dialogflow_v2.services.versions.async_client import VersionsAsyncClient + +from google.cloud.dialogflow_v2.types.agent import Agent +from google.cloud.dialogflow_v2.types.agent import DeleteAgentRequest +from google.cloud.dialogflow_v2.types.agent import ExportAgentRequest +from google.cloud.dialogflow_v2.types.agent import ExportAgentResponse +from google.cloud.dialogflow_v2.types.agent import GetAgentRequest +from google.cloud.dialogflow_v2.types.agent import GetValidationResultRequest +from google.cloud.dialogflow_v2.types.agent import ImportAgentRequest +from google.cloud.dialogflow_v2.types.agent import RestoreAgentRequest +from google.cloud.dialogflow_v2.types.agent import SearchAgentsRequest +from google.cloud.dialogflow_v2.types.agent import SearchAgentsResponse +from google.cloud.dialogflow_v2.types.agent import SetAgentRequest +from google.cloud.dialogflow_v2.types.agent import TrainAgentRequest +from google.cloud.dialogflow_v2.types.answer_record import AgentAssistantFeedback +from google.cloud.dialogflow_v2.types.answer_record import AgentAssistantRecord +from google.cloud.dialogflow_v2.types.answer_record import AnswerFeedback +from google.cloud.dialogflow_v2.types.answer_record import AnswerRecord +from google.cloud.dialogflow_v2.types.answer_record import ListAnswerRecordsRequest +from google.cloud.dialogflow_v2.types.answer_record import ListAnswerRecordsResponse +from google.cloud.dialogflow_v2.types.answer_record import UpdateAnswerRecordRequest +from google.cloud.dialogflow_v2.types.audio_config import InputAudioConfig +from google.cloud.dialogflow_v2.types.audio_config import OutputAudioConfig +from google.cloud.dialogflow_v2.types.audio_config import SpeechContext +from google.cloud.dialogflow_v2.types.audio_config import SpeechToTextConfig +from google.cloud.dialogflow_v2.types.audio_config import SpeechWordInfo +from google.cloud.dialogflow_v2.types.audio_config import SynthesizeSpeechConfig +from google.cloud.dialogflow_v2.types.audio_config import VoiceSelectionParams +from google.cloud.dialogflow_v2.types.audio_config import AudioEncoding +from google.cloud.dialogflow_v2.types.audio_config import OutputAudioEncoding +from google.cloud.dialogflow_v2.types.audio_config import SpeechModelVariant +from google.cloud.dialogflow_v2.types.audio_config import SsmlVoiceGender +from google.cloud.dialogflow_v2.types.context import Context +from google.cloud.dialogflow_v2.types.context import CreateContextRequest +from google.cloud.dialogflow_v2.types.context import DeleteAllContextsRequest +from google.cloud.dialogflow_v2.types.context import DeleteContextRequest +from google.cloud.dialogflow_v2.types.context import GetContextRequest +from google.cloud.dialogflow_v2.types.context import ListContextsRequest +from google.cloud.dialogflow_v2.types.context import ListContextsResponse +from google.cloud.dialogflow_v2.types.context import UpdateContextRequest +from google.cloud.dialogflow_v2.types.conversation import CompleteConversationRequest +from google.cloud.dialogflow_v2.types.conversation import Conversation +from google.cloud.dialogflow_v2.types.conversation import ConversationPhoneNumber +from google.cloud.dialogflow_v2.types.conversation import CreateConversationRequest +from google.cloud.dialogflow_v2.types.conversation import GetConversationRequest +from google.cloud.dialogflow_v2.types.conversation import ListConversationsRequest +from google.cloud.dialogflow_v2.types.conversation import ListConversationsResponse +from google.cloud.dialogflow_v2.types.conversation import ListMessagesRequest +from google.cloud.dialogflow_v2.types.conversation import ListMessagesResponse +from google.cloud.dialogflow_v2.types.conversation_event import ConversationEvent +from google.cloud.dialogflow_v2.types.conversation_profile import AutomatedAgentConfig +from google.cloud.dialogflow_v2.types.conversation_profile import ConversationProfile +from google.cloud.dialogflow_v2.types.conversation_profile import CreateConversationProfileRequest +from google.cloud.dialogflow_v2.types.conversation_profile import DeleteConversationProfileRequest +from google.cloud.dialogflow_v2.types.conversation_profile import GetConversationProfileRequest +from google.cloud.dialogflow_v2.types.conversation_profile import HumanAgentAssistantConfig +from google.cloud.dialogflow_v2.types.conversation_profile import HumanAgentHandoffConfig +from google.cloud.dialogflow_v2.types.conversation_profile import ListConversationProfilesRequest +from google.cloud.dialogflow_v2.types.conversation_profile import ListConversationProfilesResponse +from google.cloud.dialogflow_v2.types.conversation_profile import LoggingConfig +from google.cloud.dialogflow_v2.types.conversation_profile import NotificationConfig +from google.cloud.dialogflow_v2.types.conversation_profile import SuggestionFeature +from google.cloud.dialogflow_v2.types.conversation_profile import UpdateConversationProfileRequest +from google.cloud.dialogflow_v2.types.document import CreateDocumentRequest +from google.cloud.dialogflow_v2.types.document import DeleteDocumentRequest +from google.cloud.dialogflow_v2.types.document import Document +from google.cloud.dialogflow_v2.types.document import ExportDocumentRequest +from google.cloud.dialogflow_v2.types.document import GetDocumentRequest +from google.cloud.dialogflow_v2.types.document import KnowledgeOperationMetadata +from google.cloud.dialogflow_v2.types.document import ListDocumentsRequest +from google.cloud.dialogflow_v2.types.document import ListDocumentsResponse +from google.cloud.dialogflow_v2.types.document import ReloadDocumentRequest +from google.cloud.dialogflow_v2.types.document import UpdateDocumentRequest +from google.cloud.dialogflow_v2.types.entity_type import BatchCreateEntitiesRequest +from google.cloud.dialogflow_v2.types.entity_type import BatchDeleteEntitiesRequest +from google.cloud.dialogflow_v2.types.entity_type import BatchDeleteEntityTypesRequest +from google.cloud.dialogflow_v2.types.entity_type import BatchUpdateEntitiesRequest +from google.cloud.dialogflow_v2.types.entity_type import BatchUpdateEntityTypesRequest +from google.cloud.dialogflow_v2.types.entity_type import BatchUpdateEntityTypesResponse +from google.cloud.dialogflow_v2.types.entity_type import CreateEntityTypeRequest +from google.cloud.dialogflow_v2.types.entity_type import DeleteEntityTypeRequest +from google.cloud.dialogflow_v2.types.entity_type import EntityType +from google.cloud.dialogflow_v2.types.entity_type import EntityTypeBatch +from google.cloud.dialogflow_v2.types.entity_type import GetEntityTypeRequest +from google.cloud.dialogflow_v2.types.entity_type import ListEntityTypesRequest +from google.cloud.dialogflow_v2.types.entity_type import ListEntityTypesResponse +from google.cloud.dialogflow_v2.types.entity_type import UpdateEntityTypeRequest +from google.cloud.dialogflow_v2.types.environment import CreateEnvironmentRequest +from google.cloud.dialogflow_v2.types.environment import DeleteEnvironmentRequest +from google.cloud.dialogflow_v2.types.environment import Environment +from google.cloud.dialogflow_v2.types.environment import EnvironmentHistory +from google.cloud.dialogflow_v2.types.environment import GetEnvironmentHistoryRequest +from google.cloud.dialogflow_v2.types.environment import GetEnvironmentRequest +from google.cloud.dialogflow_v2.types.environment import ListEnvironmentsRequest +from google.cloud.dialogflow_v2.types.environment import ListEnvironmentsResponse +from google.cloud.dialogflow_v2.types.environment import TextToSpeechSettings +from google.cloud.dialogflow_v2.types.environment import UpdateEnvironmentRequest +from google.cloud.dialogflow_v2.types.fulfillment import Fulfillment +from google.cloud.dialogflow_v2.types.fulfillment import GetFulfillmentRequest +from google.cloud.dialogflow_v2.types.fulfillment import UpdateFulfillmentRequest +from google.cloud.dialogflow_v2.types.gcs import GcsDestination +from google.cloud.dialogflow_v2.types.human_agent_assistant_event import HumanAgentAssistantEvent +from google.cloud.dialogflow_v2.types.intent import BatchDeleteIntentsRequest +from google.cloud.dialogflow_v2.types.intent import BatchUpdateIntentsRequest +from google.cloud.dialogflow_v2.types.intent import BatchUpdateIntentsResponse +from google.cloud.dialogflow_v2.types.intent import CreateIntentRequest +from google.cloud.dialogflow_v2.types.intent import DeleteIntentRequest +from google.cloud.dialogflow_v2.types.intent import GetIntentRequest +from google.cloud.dialogflow_v2.types.intent import Intent +from google.cloud.dialogflow_v2.types.intent import IntentBatch +from google.cloud.dialogflow_v2.types.intent import ListIntentsRequest +from google.cloud.dialogflow_v2.types.intent import ListIntentsResponse +from google.cloud.dialogflow_v2.types.intent import UpdateIntentRequest +from google.cloud.dialogflow_v2.types.intent import IntentView +from google.cloud.dialogflow_v2.types.knowledge_base import CreateKnowledgeBaseRequest +from google.cloud.dialogflow_v2.types.knowledge_base import DeleteKnowledgeBaseRequest +from google.cloud.dialogflow_v2.types.knowledge_base import GetKnowledgeBaseRequest +from google.cloud.dialogflow_v2.types.knowledge_base import KnowledgeBase +from google.cloud.dialogflow_v2.types.knowledge_base import ListKnowledgeBasesRequest +from google.cloud.dialogflow_v2.types.knowledge_base import ListKnowledgeBasesResponse +from google.cloud.dialogflow_v2.types.knowledge_base import UpdateKnowledgeBaseRequest +from google.cloud.dialogflow_v2.types.participant import AnalyzeContentRequest +from google.cloud.dialogflow_v2.types.participant import AnalyzeContentResponse +from google.cloud.dialogflow_v2.types.participant import AnnotatedMessagePart +from google.cloud.dialogflow_v2.types.participant import ArticleAnswer +from google.cloud.dialogflow_v2.types.participant import AssistQueryParameters +from google.cloud.dialogflow_v2.types.participant import AutomatedAgentReply +from google.cloud.dialogflow_v2.types.participant import CreateParticipantRequest +from google.cloud.dialogflow_v2.types.participant import DtmfParameters +from google.cloud.dialogflow_v2.types.participant import FaqAnswer +from google.cloud.dialogflow_v2.types.participant import GetParticipantRequest +from google.cloud.dialogflow_v2.types.participant import ListParticipantsRequest +from google.cloud.dialogflow_v2.types.participant import ListParticipantsResponse +from google.cloud.dialogflow_v2.types.participant import Message +from google.cloud.dialogflow_v2.types.participant import MessageAnnotation +from google.cloud.dialogflow_v2.types.participant import OutputAudio +from google.cloud.dialogflow_v2.types.participant import Participant +from google.cloud.dialogflow_v2.types.participant import SuggestArticlesRequest +from google.cloud.dialogflow_v2.types.participant import SuggestArticlesResponse +from google.cloud.dialogflow_v2.types.participant import SuggestFaqAnswersRequest +from google.cloud.dialogflow_v2.types.participant import SuggestFaqAnswersResponse +from google.cloud.dialogflow_v2.types.participant import SuggestionResult +from google.cloud.dialogflow_v2.types.participant import UpdateParticipantRequest +from google.cloud.dialogflow_v2.types.session import DetectIntentRequest +from google.cloud.dialogflow_v2.types.session import DetectIntentResponse +from google.cloud.dialogflow_v2.types.session import EventInput +from google.cloud.dialogflow_v2.types.session import QueryInput +from google.cloud.dialogflow_v2.types.session import QueryParameters +from google.cloud.dialogflow_v2.types.session import QueryResult +from google.cloud.dialogflow_v2.types.session import Sentiment +from google.cloud.dialogflow_v2.types.session import SentimentAnalysisRequestConfig +from google.cloud.dialogflow_v2.types.session import SentimentAnalysisResult +from google.cloud.dialogflow_v2.types.session import StreamingDetectIntentRequest +from google.cloud.dialogflow_v2.types.session import StreamingDetectIntentResponse +from google.cloud.dialogflow_v2.types.session import StreamingRecognitionResult +from google.cloud.dialogflow_v2.types.session import TextInput +from google.cloud.dialogflow_v2.types.session_entity_type import CreateSessionEntityTypeRequest +from google.cloud.dialogflow_v2.types.session_entity_type import DeleteSessionEntityTypeRequest +from google.cloud.dialogflow_v2.types.session_entity_type import GetSessionEntityTypeRequest +from google.cloud.dialogflow_v2.types.session_entity_type import ListSessionEntityTypesRequest +from google.cloud.dialogflow_v2.types.session_entity_type import ListSessionEntityTypesResponse +from google.cloud.dialogflow_v2.types.session_entity_type import SessionEntityType +from google.cloud.dialogflow_v2.types.session_entity_type import UpdateSessionEntityTypeRequest +from google.cloud.dialogflow_v2.types.validation_result import ValidationError +from google.cloud.dialogflow_v2.types.validation_result import ValidationResult +from google.cloud.dialogflow_v2.types.version import CreateVersionRequest +from google.cloud.dialogflow_v2.types.version import DeleteVersionRequest +from google.cloud.dialogflow_v2.types.version import GetVersionRequest +from google.cloud.dialogflow_v2.types.version import ListVersionsRequest +from google.cloud.dialogflow_v2.types.version import ListVersionsResponse +from google.cloud.dialogflow_v2.types.version import UpdateVersionRequest +from google.cloud.dialogflow_v2.types.version import Version +from google.cloud.dialogflow_v2.types.webhook import OriginalDetectIntentRequest +from google.cloud.dialogflow_v2.types.webhook import WebhookRequest +from google.cloud.dialogflow_v2.types.webhook import WebhookResponse + +__all__ = ('AgentsClient', + 'AgentsAsyncClient', + 'AnswerRecordsClient', + 'AnswerRecordsAsyncClient', + 'ContextsClient', + 'ContextsAsyncClient', + 'ConversationProfilesClient', + 'ConversationProfilesAsyncClient', + 'ConversationsClient', + 'ConversationsAsyncClient', + 'DocumentsClient', + 'DocumentsAsyncClient', + 'EntityTypesClient', + 'EntityTypesAsyncClient', + 'EnvironmentsClient', + 'EnvironmentsAsyncClient', + 'FulfillmentsClient', + 'FulfillmentsAsyncClient', + 'IntentsClient', + 'IntentsAsyncClient', + 'KnowledgeBasesClient', + 'KnowledgeBasesAsyncClient', + 'ParticipantsClient', + 'ParticipantsAsyncClient', + 'SessionEntityTypesClient', + 'SessionEntityTypesAsyncClient', + 'SessionsClient', + 'SessionsAsyncClient', + 'VersionsClient', + 'VersionsAsyncClient', + 'Agent', + 'DeleteAgentRequest', + 'ExportAgentRequest', + 'ExportAgentResponse', + 'GetAgentRequest', + 'GetValidationResultRequest', + 'ImportAgentRequest', + 'RestoreAgentRequest', + 'SearchAgentsRequest', + 'SearchAgentsResponse', + 'SetAgentRequest', + 'TrainAgentRequest', + 'AgentAssistantFeedback', + 'AgentAssistantRecord', + 'AnswerFeedback', + 'AnswerRecord', + 'ListAnswerRecordsRequest', + 'ListAnswerRecordsResponse', + 'UpdateAnswerRecordRequest', + 'InputAudioConfig', + 'OutputAudioConfig', + 'SpeechContext', + 'SpeechToTextConfig', + 'SpeechWordInfo', + 'SynthesizeSpeechConfig', + 'VoiceSelectionParams', + 'AudioEncoding', + 'OutputAudioEncoding', + 'SpeechModelVariant', + 'SsmlVoiceGender', + 'Context', + 'CreateContextRequest', + 'DeleteAllContextsRequest', + 'DeleteContextRequest', + 'GetContextRequest', + 'ListContextsRequest', + 'ListContextsResponse', + 'UpdateContextRequest', + 'CompleteConversationRequest', + 'Conversation', + 'ConversationPhoneNumber', + 'CreateConversationRequest', + 'GetConversationRequest', + 'ListConversationsRequest', + 'ListConversationsResponse', + 'ListMessagesRequest', + 'ListMessagesResponse', + 'ConversationEvent', + 'AutomatedAgentConfig', + 'ConversationProfile', + 'CreateConversationProfileRequest', + 'DeleteConversationProfileRequest', + 'GetConversationProfileRequest', + 'HumanAgentAssistantConfig', + 'HumanAgentHandoffConfig', + 'ListConversationProfilesRequest', + 'ListConversationProfilesResponse', + 'LoggingConfig', + 'NotificationConfig', + 'SuggestionFeature', + 'UpdateConversationProfileRequest', + 'CreateDocumentRequest', + 'DeleteDocumentRequest', + 'Document', + 'ExportDocumentRequest', + 'GetDocumentRequest', + 'KnowledgeOperationMetadata', + 'ListDocumentsRequest', + 'ListDocumentsResponse', + 'ReloadDocumentRequest', + 'UpdateDocumentRequest', + 'BatchCreateEntitiesRequest', + 'BatchDeleteEntitiesRequest', + 'BatchDeleteEntityTypesRequest', + 'BatchUpdateEntitiesRequest', + 'BatchUpdateEntityTypesRequest', + 'BatchUpdateEntityTypesResponse', + 'CreateEntityTypeRequest', + 'DeleteEntityTypeRequest', + 'EntityType', + 'EntityTypeBatch', + 'GetEntityTypeRequest', + 'ListEntityTypesRequest', + 'ListEntityTypesResponse', + 'UpdateEntityTypeRequest', + 'CreateEnvironmentRequest', + 'DeleteEnvironmentRequest', + 'Environment', + 'EnvironmentHistory', + 'GetEnvironmentHistoryRequest', + 'GetEnvironmentRequest', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'TextToSpeechSettings', + 'UpdateEnvironmentRequest', + 'Fulfillment', + 'GetFulfillmentRequest', + 'UpdateFulfillmentRequest', + 'GcsDestination', + 'HumanAgentAssistantEvent', + 'BatchDeleteIntentsRequest', + 'BatchUpdateIntentsRequest', + 'BatchUpdateIntentsResponse', + 'CreateIntentRequest', + 'DeleteIntentRequest', + 'GetIntentRequest', + 'Intent', + 'IntentBatch', + 'ListIntentsRequest', + 'ListIntentsResponse', + 'UpdateIntentRequest', + 'IntentView', + 'CreateKnowledgeBaseRequest', + 'DeleteKnowledgeBaseRequest', + 'GetKnowledgeBaseRequest', + 'KnowledgeBase', + 'ListKnowledgeBasesRequest', + 'ListKnowledgeBasesResponse', + 'UpdateKnowledgeBaseRequest', + 'AnalyzeContentRequest', + 'AnalyzeContentResponse', + 'AnnotatedMessagePart', + 'ArticleAnswer', + 'AssistQueryParameters', + 'AutomatedAgentReply', + 'CreateParticipantRequest', + 'DtmfParameters', + 'FaqAnswer', + 'GetParticipantRequest', + 'ListParticipantsRequest', + 'ListParticipantsResponse', + 'Message', + 'MessageAnnotation', + 'OutputAudio', + 'Participant', + 'SuggestArticlesRequest', + 'SuggestArticlesResponse', + 'SuggestFaqAnswersRequest', + 'SuggestFaqAnswersResponse', + 'SuggestionResult', + 'UpdateParticipantRequest', + 'DetectIntentRequest', + 'DetectIntentResponse', + 'EventInput', + 'QueryInput', + 'QueryParameters', + 'QueryResult', + 'Sentiment', + 'SentimentAnalysisRequestConfig', + 'SentimentAnalysisResult', + 'StreamingDetectIntentRequest', + 'StreamingDetectIntentResponse', + 'StreamingRecognitionResult', + 'TextInput', + 'CreateSessionEntityTypeRequest', + 'DeleteSessionEntityTypeRequest', + 'GetSessionEntityTypeRequest', + 'ListSessionEntityTypesRequest', + 'ListSessionEntityTypesResponse', + 'SessionEntityType', + 'UpdateSessionEntityTypeRequest', + 'ValidationError', + 'ValidationResult', + 'CreateVersionRequest', + 'DeleteVersionRequest', + 'GetVersionRequest', + 'ListVersionsRequest', + 'ListVersionsResponse', + 'UpdateVersionRequest', + 'Version', + 'OriginalDetectIntentRequest', + 'WebhookRequest', + 'WebhookResponse', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow/py.typed b/owl-bot-staging/v2/google/cloud/dialogflow/py.typed new file mode 100644 index 000000000..2c6e5af62 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-dialogflow package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/__init__.py new file mode 100644 index 000000000..8052ba7f8 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/__init__.py @@ -0,0 +1,426 @@ +# -*- 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.agents import AgentsClient +from .services.agents import AgentsAsyncClient +from .services.answer_records import AnswerRecordsClient +from .services.answer_records import AnswerRecordsAsyncClient +from .services.contexts import ContextsClient +from .services.contexts import ContextsAsyncClient +from .services.conversation_profiles import ConversationProfilesClient +from .services.conversation_profiles import ConversationProfilesAsyncClient +from .services.conversations import ConversationsClient +from .services.conversations import ConversationsAsyncClient +from .services.documents import DocumentsClient +from .services.documents import DocumentsAsyncClient +from .services.entity_types import EntityTypesClient +from .services.entity_types import EntityTypesAsyncClient +from .services.environments import EnvironmentsClient +from .services.environments import EnvironmentsAsyncClient +from .services.fulfillments import FulfillmentsClient +from .services.fulfillments import FulfillmentsAsyncClient +from .services.intents import IntentsClient +from .services.intents import IntentsAsyncClient +from .services.knowledge_bases import KnowledgeBasesClient +from .services.knowledge_bases import KnowledgeBasesAsyncClient +from .services.participants import ParticipantsClient +from .services.participants import ParticipantsAsyncClient +from .services.session_entity_types import SessionEntityTypesClient +from .services.session_entity_types import SessionEntityTypesAsyncClient +from .services.sessions import SessionsClient +from .services.sessions import SessionsAsyncClient +from .services.versions import VersionsClient +from .services.versions import VersionsAsyncClient + +from .types.agent import Agent +from .types.agent import DeleteAgentRequest +from .types.agent import ExportAgentRequest +from .types.agent import ExportAgentResponse +from .types.agent import GetAgentRequest +from .types.agent import GetValidationResultRequest +from .types.agent import ImportAgentRequest +from .types.agent import RestoreAgentRequest +from .types.agent import SearchAgentsRequest +from .types.agent import SearchAgentsResponse +from .types.agent import SetAgentRequest +from .types.agent import TrainAgentRequest +from .types.answer_record import AgentAssistantFeedback +from .types.answer_record import AgentAssistantRecord +from .types.answer_record import AnswerFeedback +from .types.answer_record import AnswerRecord +from .types.answer_record import ListAnswerRecordsRequest +from .types.answer_record import ListAnswerRecordsResponse +from .types.answer_record import UpdateAnswerRecordRequest +from .types.audio_config import InputAudioConfig +from .types.audio_config import OutputAudioConfig +from .types.audio_config import SpeechContext +from .types.audio_config import SpeechToTextConfig +from .types.audio_config import SpeechWordInfo +from .types.audio_config import SynthesizeSpeechConfig +from .types.audio_config import VoiceSelectionParams +from .types.audio_config import AudioEncoding +from .types.audio_config import OutputAudioEncoding +from .types.audio_config import SpeechModelVariant +from .types.audio_config import SsmlVoiceGender +from .types.context import Context +from .types.context import CreateContextRequest +from .types.context import DeleteAllContextsRequest +from .types.context import DeleteContextRequest +from .types.context import GetContextRequest +from .types.context import ListContextsRequest +from .types.context import ListContextsResponse +from .types.context import UpdateContextRequest +from .types.conversation import CompleteConversationRequest +from .types.conversation import Conversation +from .types.conversation import ConversationPhoneNumber +from .types.conversation import CreateConversationRequest +from .types.conversation import GetConversationRequest +from .types.conversation import ListConversationsRequest +from .types.conversation import ListConversationsResponse +from .types.conversation import ListMessagesRequest +from .types.conversation import ListMessagesResponse +from .types.conversation_event import ConversationEvent +from .types.conversation_profile import AutomatedAgentConfig +from .types.conversation_profile import ConversationProfile +from .types.conversation_profile import CreateConversationProfileRequest +from .types.conversation_profile import DeleteConversationProfileRequest +from .types.conversation_profile import GetConversationProfileRequest +from .types.conversation_profile import HumanAgentAssistantConfig +from .types.conversation_profile import HumanAgentHandoffConfig +from .types.conversation_profile import ListConversationProfilesRequest +from .types.conversation_profile import ListConversationProfilesResponse +from .types.conversation_profile import LoggingConfig +from .types.conversation_profile import NotificationConfig +from .types.conversation_profile import SuggestionFeature +from .types.conversation_profile import UpdateConversationProfileRequest +from .types.document import CreateDocumentRequest +from .types.document import DeleteDocumentRequest +from .types.document import Document +from .types.document import ExportDocumentRequest +from .types.document import GetDocumentRequest +from .types.document import KnowledgeOperationMetadata +from .types.document import ListDocumentsRequest +from .types.document import ListDocumentsResponse +from .types.document import ReloadDocumentRequest +from .types.document import UpdateDocumentRequest +from .types.entity_type import BatchCreateEntitiesRequest +from .types.entity_type import BatchDeleteEntitiesRequest +from .types.entity_type import BatchDeleteEntityTypesRequest +from .types.entity_type import BatchUpdateEntitiesRequest +from .types.entity_type import BatchUpdateEntityTypesRequest +from .types.entity_type import BatchUpdateEntityTypesResponse +from .types.entity_type import CreateEntityTypeRequest +from .types.entity_type import DeleteEntityTypeRequest +from .types.entity_type import EntityType +from .types.entity_type import EntityTypeBatch +from .types.entity_type import GetEntityTypeRequest +from .types.entity_type import ListEntityTypesRequest +from .types.entity_type import ListEntityTypesResponse +from .types.entity_type import UpdateEntityTypeRequest +from .types.environment import CreateEnvironmentRequest +from .types.environment import DeleteEnvironmentRequest +from .types.environment import Environment +from .types.environment import EnvironmentHistory +from .types.environment import GetEnvironmentHistoryRequest +from .types.environment import GetEnvironmentRequest +from .types.environment import ListEnvironmentsRequest +from .types.environment import ListEnvironmentsResponse +from .types.environment import TextToSpeechSettings +from .types.environment import UpdateEnvironmentRequest +from .types.fulfillment import Fulfillment +from .types.fulfillment import GetFulfillmentRequest +from .types.fulfillment import UpdateFulfillmentRequest +from .types.gcs import GcsDestination +from .types.human_agent_assistant_event import HumanAgentAssistantEvent +from .types.intent import BatchDeleteIntentsRequest +from .types.intent import BatchUpdateIntentsRequest +from .types.intent import BatchUpdateIntentsResponse +from .types.intent import CreateIntentRequest +from .types.intent import DeleteIntentRequest +from .types.intent import GetIntentRequest +from .types.intent import Intent +from .types.intent import IntentBatch +from .types.intent import ListIntentsRequest +from .types.intent import ListIntentsResponse +from .types.intent import UpdateIntentRequest +from .types.intent import IntentView +from .types.knowledge_base import CreateKnowledgeBaseRequest +from .types.knowledge_base import DeleteKnowledgeBaseRequest +from .types.knowledge_base import GetKnowledgeBaseRequest +from .types.knowledge_base import KnowledgeBase +from .types.knowledge_base import ListKnowledgeBasesRequest +from .types.knowledge_base import ListKnowledgeBasesResponse +from .types.knowledge_base import UpdateKnowledgeBaseRequest +from .types.participant import AnalyzeContentRequest +from .types.participant import AnalyzeContentResponse +from .types.participant import AnnotatedMessagePart +from .types.participant import ArticleAnswer +from .types.participant import AssistQueryParameters +from .types.participant import AutomatedAgentReply +from .types.participant import CreateParticipantRequest +from .types.participant import DtmfParameters +from .types.participant import FaqAnswer +from .types.participant import GetParticipantRequest +from .types.participant import ListParticipantsRequest +from .types.participant import ListParticipantsResponse +from .types.participant import Message +from .types.participant import MessageAnnotation +from .types.participant import OutputAudio +from .types.participant import Participant +from .types.participant import SuggestArticlesRequest +from .types.participant import SuggestArticlesResponse +from .types.participant import SuggestFaqAnswersRequest +from .types.participant import SuggestFaqAnswersResponse +from .types.participant import SuggestionResult +from .types.participant import UpdateParticipantRequest +from .types.session import DetectIntentRequest +from .types.session import DetectIntentResponse +from .types.session import EventInput +from .types.session import QueryInput +from .types.session import QueryParameters +from .types.session import QueryResult +from .types.session import Sentiment +from .types.session import SentimentAnalysisRequestConfig +from .types.session import SentimentAnalysisResult +from .types.session import StreamingDetectIntentRequest +from .types.session import StreamingDetectIntentResponse +from .types.session import StreamingRecognitionResult +from .types.session import TextInput +from .types.session_entity_type import CreateSessionEntityTypeRequest +from .types.session_entity_type import DeleteSessionEntityTypeRequest +from .types.session_entity_type import GetSessionEntityTypeRequest +from .types.session_entity_type import ListSessionEntityTypesRequest +from .types.session_entity_type import ListSessionEntityTypesResponse +from .types.session_entity_type import SessionEntityType +from .types.session_entity_type import UpdateSessionEntityTypeRequest +from .types.validation_result import ValidationError +from .types.validation_result import ValidationResult +from .types.version import CreateVersionRequest +from .types.version import DeleteVersionRequest +from .types.version import GetVersionRequest +from .types.version import ListVersionsRequest +from .types.version import ListVersionsResponse +from .types.version import UpdateVersionRequest +from .types.version import Version +from .types.webhook import OriginalDetectIntentRequest +from .types.webhook import WebhookRequest +from .types.webhook import WebhookResponse + +__all__ = ( + 'AgentsAsyncClient', + 'AnswerRecordsAsyncClient', + 'ContextsAsyncClient', + 'ConversationProfilesAsyncClient', + 'ConversationsAsyncClient', + 'DocumentsAsyncClient', + 'EntityTypesAsyncClient', + 'EnvironmentsAsyncClient', + 'FulfillmentsAsyncClient', + 'IntentsAsyncClient', + 'KnowledgeBasesAsyncClient', + 'ParticipantsAsyncClient', + 'SessionEntityTypesAsyncClient', + 'SessionsAsyncClient', + 'VersionsAsyncClient', +'Agent', +'AgentAssistantFeedback', +'AgentAssistantRecord', +'AgentsClient', +'AnalyzeContentRequest', +'AnalyzeContentResponse', +'AnnotatedMessagePart', +'AnswerFeedback', +'AnswerRecord', +'AnswerRecordsClient', +'ArticleAnswer', +'AssistQueryParameters', +'AudioEncoding', +'AutomatedAgentConfig', +'AutomatedAgentReply', +'BatchCreateEntitiesRequest', +'BatchDeleteEntitiesRequest', +'BatchDeleteEntityTypesRequest', +'BatchDeleteIntentsRequest', +'BatchUpdateEntitiesRequest', +'BatchUpdateEntityTypesRequest', +'BatchUpdateEntityTypesResponse', +'BatchUpdateIntentsRequest', +'BatchUpdateIntentsResponse', +'CompleteConversationRequest', +'Context', +'ContextsClient', +'Conversation', +'ConversationEvent', +'ConversationPhoneNumber', +'ConversationProfile', +'ConversationProfilesClient', +'ConversationsClient', +'CreateContextRequest', +'CreateConversationProfileRequest', +'CreateConversationRequest', +'CreateDocumentRequest', +'CreateEntityTypeRequest', +'CreateEnvironmentRequest', +'CreateIntentRequest', +'CreateKnowledgeBaseRequest', +'CreateParticipantRequest', +'CreateSessionEntityTypeRequest', +'CreateVersionRequest', +'DeleteAgentRequest', +'DeleteAllContextsRequest', +'DeleteContextRequest', +'DeleteConversationProfileRequest', +'DeleteDocumentRequest', +'DeleteEntityTypeRequest', +'DeleteEnvironmentRequest', +'DeleteIntentRequest', +'DeleteKnowledgeBaseRequest', +'DeleteSessionEntityTypeRequest', +'DeleteVersionRequest', +'DetectIntentRequest', +'DetectIntentResponse', +'Document', +'DocumentsClient', +'DtmfParameters', +'EntityType', +'EntityTypeBatch', +'EntityTypesClient', +'Environment', +'EnvironmentHistory', +'EnvironmentsClient', +'EventInput', +'ExportAgentRequest', +'ExportAgentResponse', +'ExportDocumentRequest', +'FaqAnswer', +'Fulfillment', +'FulfillmentsClient', +'GcsDestination', +'GetAgentRequest', +'GetContextRequest', +'GetConversationProfileRequest', +'GetConversationRequest', +'GetDocumentRequest', +'GetEntityTypeRequest', +'GetEnvironmentHistoryRequest', +'GetEnvironmentRequest', +'GetFulfillmentRequest', +'GetIntentRequest', +'GetKnowledgeBaseRequest', +'GetParticipantRequest', +'GetSessionEntityTypeRequest', +'GetValidationResultRequest', +'GetVersionRequest', +'HumanAgentAssistantConfig', +'HumanAgentAssistantEvent', +'HumanAgentHandoffConfig', +'ImportAgentRequest', +'InputAudioConfig', +'Intent', +'IntentBatch', +'IntentView', +'IntentsClient', +'KnowledgeBase', +'KnowledgeBasesClient', +'KnowledgeOperationMetadata', +'ListAnswerRecordsRequest', +'ListAnswerRecordsResponse', +'ListContextsRequest', +'ListContextsResponse', +'ListConversationProfilesRequest', +'ListConversationProfilesResponse', +'ListConversationsRequest', +'ListConversationsResponse', +'ListDocumentsRequest', +'ListDocumentsResponse', +'ListEntityTypesRequest', +'ListEntityTypesResponse', +'ListEnvironmentsRequest', +'ListEnvironmentsResponse', +'ListIntentsRequest', +'ListIntentsResponse', +'ListKnowledgeBasesRequest', +'ListKnowledgeBasesResponse', +'ListMessagesRequest', +'ListMessagesResponse', +'ListParticipantsRequest', +'ListParticipantsResponse', +'ListSessionEntityTypesRequest', +'ListSessionEntityTypesResponse', +'ListVersionsRequest', +'ListVersionsResponse', +'LoggingConfig', +'Message', +'MessageAnnotation', +'NotificationConfig', +'OriginalDetectIntentRequest', +'OutputAudio', +'OutputAudioConfig', +'OutputAudioEncoding', +'Participant', +'ParticipantsClient', +'QueryInput', +'QueryParameters', +'QueryResult', +'ReloadDocumentRequest', +'RestoreAgentRequest', +'SearchAgentsRequest', +'SearchAgentsResponse', +'Sentiment', +'SentimentAnalysisRequestConfig', +'SentimentAnalysisResult', +'SessionEntityType', +'SessionEntityTypesClient', +'SessionsClient', +'SetAgentRequest', +'SpeechContext', +'SpeechModelVariant', +'SpeechToTextConfig', +'SpeechWordInfo', +'SsmlVoiceGender', +'StreamingDetectIntentRequest', +'StreamingDetectIntentResponse', +'StreamingRecognitionResult', +'SuggestArticlesRequest', +'SuggestArticlesResponse', +'SuggestFaqAnswersRequest', +'SuggestFaqAnswersResponse', +'SuggestionFeature', +'SuggestionResult', +'SynthesizeSpeechConfig', +'TextInput', +'TextToSpeechSettings', +'TrainAgentRequest', +'UpdateAnswerRecordRequest', +'UpdateContextRequest', +'UpdateConversationProfileRequest', +'UpdateDocumentRequest', +'UpdateEntityTypeRequest', +'UpdateEnvironmentRequest', +'UpdateFulfillmentRequest', +'UpdateIntentRequest', +'UpdateKnowledgeBaseRequest', +'UpdateParticipantRequest', +'UpdateSessionEntityTypeRequest', +'UpdateVersionRequest', +'ValidationError', +'ValidationResult', +'Version', +'VersionsClient', +'VoiceSelectionParams', +'WebhookRequest', +'WebhookResponse', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/gapic_metadata.json b/owl-bot-staging/v2/google/cloud/dialogflow_v2/gapic_metadata.json new file mode 100644 index 000000000..bedcfbda7 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/gapic_metadata.json @@ -0,0 +1,1049 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.dialogflow_v2", + "protoPackage": "google.cloud.dialogflow.v2", + "schema": "1.0", + "services": { + "Agents": { + "clients": { + "grpc": { + "libraryClient": "AgentsClient", + "rpcs": { + "DeleteAgent": { + "methods": [ + "delete_agent" + ] + }, + "ExportAgent": { + "methods": [ + "export_agent" + ] + }, + "GetAgent": { + "methods": [ + "get_agent" + ] + }, + "GetValidationResult": { + "methods": [ + "get_validation_result" + ] + }, + "ImportAgent": { + "methods": [ + "import_agent" + ] + }, + "RestoreAgent": { + "methods": [ + "restore_agent" + ] + }, + "SearchAgents": { + "methods": [ + "search_agents" + ] + }, + "SetAgent": { + "methods": [ + "set_agent" + ] + }, + "TrainAgent": { + "methods": [ + "train_agent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AgentsAsyncClient", + "rpcs": { + "DeleteAgent": { + "methods": [ + "delete_agent" + ] + }, + "ExportAgent": { + "methods": [ + "export_agent" + ] + }, + "GetAgent": { + "methods": [ + "get_agent" + ] + }, + "GetValidationResult": { + "methods": [ + "get_validation_result" + ] + }, + "ImportAgent": { + "methods": [ + "import_agent" + ] + }, + "RestoreAgent": { + "methods": [ + "restore_agent" + ] + }, + "SearchAgents": { + "methods": [ + "search_agents" + ] + }, + "SetAgent": { + "methods": [ + "set_agent" + ] + }, + "TrainAgent": { + "methods": [ + "train_agent" + ] + } + } + } + } + }, + "AnswerRecords": { + "clients": { + "grpc": { + "libraryClient": "AnswerRecordsClient", + "rpcs": { + "ListAnswerRecords": { + "methods": [ + "list_answer_records" + ] + }, + "UpdateAnswerRecord": { + "methods": [ + "update_answer_record" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AnswerRecordsAsyncClient", + "rpcs": { + "ListAnswerRecords": { + "methods": [ + "list_answer_records" + ] + }, + "UpdateAnswerRecord": { + "methods": [ + "update_answer_record" + ] + } + } + } + } + }, + "Contexts": { + "clients": { + "grpc": { + "libraryClient": "ContextsClient", + "rpcs": { + "CreateContext": { + "methods": [ + "create_context" + ] + }, + "DeleteAllContexts": { + "methods": [ + "delete_all_contexts" + ] + }, + "DeleteContext": { + "methods": [ + "delete_context" + ] + }, + "GetContext": { + "methods": [ + "get_context" + ] + }, + "ListContexts": { + "methods": [ + "list_contexts" + ] + }, + "UpdateContext": { + "methods": [ + "update_context" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ContextsAsyncClient", + "rpcs": { + "CreateContext": { + "methods": [ + "create_context" + ] + }, + "DeleteAllContexts": { + "methods": [ + "delete_all_contexts" + ] + }, + "DeleteContext": { + "methods": [ + "delete_context" + ] + }, + "GetContext": { + "methods": [ + "get_context" + ] + }, + "ListContexts": { + "methods": [ + "list_contexts" + ] + }, + "UpdateContext": { + "methods": [ + "update_context" + ] + } + } + } + } + }, + "ConversationProfiles": { + "clients": { + "grpc": { + "libraryClient": "ConversationProfilesClient", + "rpcs": { + "CreateConversationProfile": { + "methods": [ + "create_conversation_profile" + ] + }, + "DeleteConversationProfile": { + "methods": [ + "delete_conversation_profile" + ] + }, + "GetConversationProfile": { + "methods": [ + "get_conversation_profile" + ] + }, + "ListConversationProfiles": { + "methods": [ + "list_conversation_profiles" + ] + }, + "UpdateConversationProfile": { + "methods": [ + "update_conversation_profile" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ConversationProfilesAsyncClient", + "rpcs": { + "CreateConversationProfile": { + "methods": [ + "create_conversation_profile" + ] + }, + "DeleteConversationProfile": { + "methods": [ + "delete_conversation_profile" + ] + }, + "GetConversationProfile": { + "methods": [ + "get_conversation_profile" + ] + }, + "ListConversationProfiles": { + "methods": [ + "list_conversation_profiles" + ] + }, + "UpdateConversationProfile": { + "methods": [ + "update_conversation_profile" + ] + } + } + } + } + }, + "Conversations": { + "clients": { + "grpc": { + "libraryClient": "ConversationsClient", + "rpcs": { + "CompleteConversation": { + "methods": [ + "complete_conversation" + ] + }, + "CreateConversation": { + "methods": [ + "create_conversation" + ] + }, + "GetConversation": { + "methods": [ + "get_conversation" + ] + }, + "ListConversations": { + "methods": [ + "list_conversations" + ] + }, + "ListMessages": { + "methods": [ + "list_messages" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ConversationsAsyncClient", + "rpcs": { + "CompleteConversation": { + "methods": [ + "complete_conversation" + ] + }, + "CreateConversation": { + "methods": [ + "create_conversation" + ] + }, + "GetConversation": { + "methods": [ + "get_conversation" + ] + }, + "ListConversations": { + "methods": [ + "list_conversations" + ] + }, + "ListMessages": { + "methods": [ + "list_messages" + ] + } + } + } + } + }, + "Documents": { + "clients": { + "grpc": { + "libraryClient": "DocumentsClient", + "rpcs": { + "CreateDocument": { + "methods": [ + "create_document" + ] + }, + "DeleteDocument": { + "methods": [ + "delete_document" + ] + }, + "ExportDocument": { + "methods": [ + "export_document" + ] + }, + "GetDocument": { + "methods": [ + "get_document" + ] + }, + "ListDocuments": { + "methods": [ + "list_documents" + ] + }, + "ReloadDocument": { + "methods": [ + "reload_document" + ] + }, + "UpdateDocument": { + "methods": [ + "update_document" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DocumentsAsyncClient", + "rpcs": { + "CreateDocument": { + "methods": [ + "create_document" + ] + }, + "DeleteDocument": { + "methods": [ + "delete_document" + ] + }, + "ExportDocument": { + "methods": [ + "export_document" + ] + }, + "GetDocument": { + "methods": [ + "get_document" + ] + }, + "ListDocuments": { + "methods": [ + "list_documents" + ] + }, + "ReloadDocument": { + "methods": [ + "reload_document" + ] + }, + "UpdateDocument": { + "methods": [ + "update_document" + ] + } + } + } + } + }, + "EntityTypes": { + "clients": { + "grpc": { + "libraryClient": "EntityTypesClient", + "rpcs": { + "BatchCreateEntities": { + "methods": [ + "batch_create_entities" + ] + }, + "BatchDeleteEntities": { + "methods": [ + "batch_delete_entities" + ] + }, + "BatchDeleteEntityTypes": { + "methods": [ + "batch_delete_entity_types" + ] + }, + "BatchUpdateEntities": { + "methods": [ + "batch_update_entities" + ] + }, + "BatchUpdateEntityTypes": { + "methods": [ + "batch_update_entity_types" + ] + }, + "CreateEntityType": { + "methods": [ + "create_entity_type" + ] + }, + "DeleteEntityType": { + "methods": [ + "delete_entity_type" + ] + }, + "GetEntityType": { + "methods": [ + "get_entity_type" + ] + }, + "ListEntityTypes": { + "methods": [ + "list_entity_types" + ] + }, + "UpdateEntityType": { + "methods": [ + "update_entity_type" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EntityTypesAsyncClient", + "rpcs": { + "BatchCreateEntities": { + "methods": [ + "batch_create_entities" + ] + }, + "BatchDeleteEntities": { + "methods": [ + "batch_delete_entities" + ] + }, + "BatchDeleteEntityTypes": { + "methods": [ + "batch_delete_entity_types" + ] + }, + "BatchUpdateEntities": { + "methods": [ + "batch_update_entities" + ] + }, + "BatchUpdateEntityTypes": { + "methods": [ + "batch_update_entity_types" + ] + }, + "CreateEntityType": { + "methods": [ + "create_entity_type" + ] + }, + "DeleteEntityType": { + "methods": [ + "delete_entity_type" + ] + }, + "GetEntityType": { + "methods": [ + "get_entity_type" + ] + }, + "ListEntityTypes": { + "methods": [ + "list_entity_types" + ] + }, + "UpdateEntityType": { + "methods": [ + "update_entity_type" + ] + } + } + } + } + }, + "Environments": { + "clients": { + "grpc": { + "libraryClient": "EnvironmentsClient", + "rpcs": { + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "GetEnvironmentHistory": { + "methods": [ + "get_environment_history" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EnvironmentsAsyncClient", + "rpcs": { + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "GetEnvironmentHistory": { + "methods": [ + "get_environment_history" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + } + } + }, + "Fulfillments": { + "clients": { + "grpc": { + "libraryClient": "FulfillmentsClient", + "rpcs": { + "GetFulfillment": { + "methods": [ + "get_fulfillment" + ] + }, + "UpdateFulfillment": { + "methods": [ + "update_fulfillment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "FulfillmentsAsyncClient", + "rpcs": { + "GetFulfillment": { + "methods": [ + "get_fulfillment" + ] + }, + "UpdateFulfillment": { + "methods": [ + "update_fulfillment" + ] + } + } + } + } + }, + "Intents": { + "clients": { + "grpc": { + "libraryClient": "IntentsClient", + "rpcs": { + "BatchDeleteIntents": { + "methods": [ + "batch_delete_intents" + ] + }, + "BatchUpdateIntents": { + "methods": [ + "batch_update_intents" + ] + }, + "CreateIntent": { + "methods": [ + "create_intent" + ] + }, + "DeleteIntent": { + "methods": [ + "delete_intent" + ] + }, + "GetIntent": { + "methods": [ + "get_intent" + ] + }, + "ListIntents": { + "methods": [ + "list_intents" + ] + }, + "UpdateIntent": { + "methods": [ + "update_intent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "IntentsAsyncClient", + "rpcs": { + "BatchDeleteIntents": { + "methods": [ + "batch_delete_intents" + ] + }, + "BatchUpdateIntents": { + "methods": [ + "batch_update_intents" + ] + }, + "CreateIntent": { + "methods": [ + "create_intent" + ] + }, + "DeleteIntent": { + "methods": [ + "delete_intent" + ] + }, + "GetIntent": { + "methods": [ + "get_intent" + ] + }, + "ListIntents": { + "methods": [ + "list_intents" + ] + }, + "UpdateIntent": { + "methods": [ + "update_intent" + ] + } + } + } + } + }, + "KnowledgeBases": { + "clients": { + "grpc": { + "libraryClient": "KnowledgeBasesClient", + "rpcs": { + "CreateKnowledgeBase": { + "methods": [ + "create_knowledge_base" + ] + }, + "DeleteKnowledgeBase": { + "methods": [ + "delete_knowledge_base" + ] + }, + "GetKnowledgeBase": { + "methods": [ + "get_knowledge_base" + ] + }, + "ListKnowledgeBases": { + "methods": [ + "list_knowledge_bases" + ] + }, + "UpdateKnowledgeBase": { + "methods": [ + "update_knowledge_base" + ] + } + } + }, + "grpc-async": { + "libraryClient": "KnowledgeBasesAsyncClient", + "rpcs": { + "CreateKnowledgeBase": { + "methods": [ + "create_knowledge_base" + ] + }, + "DeleteKnowledgeBase": { + "methods": [ + "delete_knowledge_base" + ] + }, + "GetKnowledgeBase": { + "methods": [ + "get_knowledge_base" + ] + }, + "ListKnowledgeBases": { + "methods": [ + "list_knowledge_bases" + ] + }, + "UpdateKnowledgeBase": { + "methods": [ + "update_knowledge_base" + ] + } + } + } + } + }, + "Participants": { + "clients": { + "grpc": { + "libraryClient": "ParticipantsClient", + "rpcs": { + "AnalyzeContent": { + "methods": [ + "analyze_content" + ] + }, + "CreateParticipant": { + "methods": [ + "create_participant" + ] + }, + "GetParticipant": { + "methods": [ + "get_participant" + ] + }, + "ListParticipants": { + "methods": [ + "list_participants" + ] + }, + "SuggestArticles": { + "methods": [ + "suggest_articles" + ] + }, + "SuggestFaqAnswers": { + "methods": [ + "suggest_faq_answers" + ] + }, + "UpdateParticipant": { + "methods": [ + "update_participant" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ParticipantsAsyncClient", + "rpcs": { + "AnalyzeContent": { + "methods": [ + "analyze_content" + ] + }, + "CreateParticipant": { + "methods": [ + "create_participant" + ] + }, + "GetParticipant": { + "methods": [ + "get_participant" + ] + }, + "ListParticipants": { + "methods": [ + "list_participants" + ] + }, + "SuggestArticles": { + "methods": [ + "suggest_articles" + ] + }, + "SuggestFaqAnswers": { + "methods": [ + "suggest_faq_answers" + ] + }, + "UpdateParticipant": { + "methods": [ + "update_participant" + ] + } + } + } + } + }, + "SessionEntityTypes": { + "clients": { + "grpc": { + "libraryClient": "SessionEntityTypesClient", + "rpcs": { + "CreateSessionEntityType": { + "methods": [ + "create_session_entity_type" + ] + }, + "DeleteSessionEntityType": { + "methods": [ + "delete_session_entity_type" + ] + }, + "GetSessionEntityType": { + "methods": [ + "get_session_entity_type" + ] + }, + "ListSessionEntityTypes": { + "methods": [ + "list_session_entity_types" + ] + }, + "UpdateSessionEntityType": { + "methods": [ + "update_session_entity_type" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SessionEntityTypesAsyncClient", + "rpcs": { + "CreateSessionEntityType": { + "methods": [ + "create_session_entity_type" + ] + }, + "DeleteSessionEntityType": { + "methods": [ + "delete_session_entity_type" + ] + }, + "GetSessionEntityType": { + "methods": [ + "get_session_entity_type" + ] + }, + "ListSessionEntityTypes": { + "methods": [ + "list_session_entity_types" + ] + }, + "UpdateSessionEntityType": { + "methods": [ + "update_session_entity_type" + ] + } + } + } + } + }, + "Sessions": { + "clients": { + "grpc": { + "libraryClient": "SessionsClient", + "rpcs": { + "DetectIntent": { + "methods": [ + "detect_intent" + ] + }, + "StreamingDetectIntent": { + "methods": [ + "streaming_detect_intent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SessionsAsyncClient", + "rpcs": { + "DetectIntent": { + "methods": [ + "detect_intent" + ] + }, + "StreamingDetectIntent": { + "methods": [ + "streaming_detect_intent" + ] + } + } + } + } + }, + "Versions": { + "clients": { + "grpc": { + "libraryClient": "VersionsClient", + "rpcs": { + "CreateVersion": { + "methods": [ + "create_version" + ] + }, + "DeleteVersion": { + "methods": [ + "delete_version" + ] + }, + "GetVersion": { + "methods": [ + "get_version" + ] + }, + "ListVersions": { + "methods": [ + "list_versions" + ] + }, + "UpdateVersion": { + "methods": [ + "update_version" + ] + } + } + }, + "grpc-async": { + "libraryClient": "VersionsAsyncClient", + "rpcs": { + "CreateVersion": { + "methods": [ + "create_version" + ] + }, + "DeleteVersion": { + "methods": [ + "delete_version" + ] + }, + "GetVersion": { + "methods": [ + "get_version" + ] + }, + "ListVersions": { + "methods": [ + "list_versions" + ] + }, + "UpdateVersion": { + "methods": [ + "update_version" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/py.typed b/owl-bot-staging/v2/google/cloud/dialogflow_v2/py.typed new file mode 100644 index 000000000..2c6e5af62 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-dialogflow package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/__init__.py new file mode 100644 index 000000000..4de65971c --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/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/v2/google/cloud/dialogflow_v2/services/agents/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/__init__.py new file mode 100644 index 000000000..057c8b80b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/__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 AgentsClient +from .async_client import AgentsAsyncClient + +__all__ = ( + 'AgentsClient', + 'AgentsAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/async_client.py new file mode 100644 index 000000000..65dc243e4 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/async_client.py @@ -0,0 +1,975 @@ +# -*- 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 + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.dialogflow_v2.services.agents import pagers +from google.cloud.dialogflow_v2.types import agent +from google.cloud.dialogflow_v2.types import agent as gcd_agent +from google.cloud.dialogflow_v2.types import validation_result +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import AgentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AgentsGrpcAsyncIOTransport +from .client import AgentsClient + + +class AgentsAsyncClient: + """Service for managing [Agents][google.cloud.dialogflow.v2.Agent].""" + + _client: AgentsClient + + DEFAULT_ENDPOINT = AgentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AgentsClient.DEFAULT_MTLS_ENDPOINT + + agent_path = staticmethod(AgentsClient.agent_path) + parse_agent_path = staticmethod(AgentsClient.parse_agent_path) + common_billing_account_path = staticmethod(AgentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AgentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AgentsClient.common_folder_path) + parse_common_folder_path = staticmethod(AgentsClient.parse_common_folder_path) + common_organization_path = staticmethod(AgentsClient.common_organization_path) + parse_common_organization_path = staticmethod(AgentsClient.parse_common_organization_path) + common_project_path = staticmethod(AgentsClient.common_project_path) + parse_common_project_path = staticmethod(AgentsClient.parse_common_project_path) + common_location_path = staticmethod(AgentsClient.common_location_path) + parse_common_location_path = staticmethod(AgentsClient.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: + AgentsAsyncClient: The constructed client. + """ + return AgentsClient.from_service_account_info.__func__(AgentsAsyncClient, 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: + AgentsAsyncClient: The constructed client. + """ + return AgentsClient.from_service_account_file.__func__(AgentsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> AgentsTransport: + """Returns the transport used by the client instance. + + Returns: + AgentsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(AgentsClient).get_transport_class, type(AgentsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, AgentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the agents 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, ~.AgentsTransport]): 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 = AgentsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_agent(self, + request: Union[agent.GetAgentRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> agent.Agent: + r"""Retrieves the specified agent. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetAgentRequest, dict]): + The request object. The request message for + [Agents.GetAgent][google.cloud.dialogflow.v2.Agents.GetAgent]. + parent (:class:`str`): + Required. The project that the agent to fetch is + associated with. Format: ``projects/``. + + 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.dialogflow_v2.types.Agent: + A Dialogflow agent is a virtual agent that handles conversations with your + end-users. It is a natural language understanding + module that understands the nuances of human + language. Dialogflow translates end-user text or + audio during a conversation to structured data that + your apps and services can understand. You design and + build a Dialogflow agent to handle the types of + conversations required for your system. + + For more information about agents, see the [Agent + guide](\ https://cloud.google.com/dialogflow/docs/agents-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is 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 = agent.GetAgentRequest(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.get_agent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_agent(self, + request: Union[gcd_agent.SetAgentRequest, dict] = None, + *, + agent: gcd_agent.Agent = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_agent.Agent: + r"""Creates/updates the specified agent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.SetAgentRequest, dict]): + The request object. The request message for + [Agents.SetAgent][google.cloud.dialogflow.v2.Agents.SetAgent]. + agent (:class:`google.cloud.dialogflow_v2.types.Agent`): + Required. The agent to update. + This corresponds to the ``agent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Agent: + A Dialogflow agent is a virtual agent that handles conversations with your + end-users. It is a natural language understanding + module that understands the nuances of human + language. Dialogflow translates end-user text or + audio during a conversation to structured data that + your apps and services can understand. You design and + build a Dialogflow agent to handle the types of + conversations required for your system. + + For more information about agents, see the [Agent + guide](\ https://cloud.google.com/dialogflow/docs/agents-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([agent]) + if request is 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 = gcd_agent.SetAgentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if agent is not None: + request.agent = agent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_agent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("agent.parent", request.agent.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_agent(self, + request: Union[agent.DeleteAgentRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified agent. + + Args: + request (Union[google.cloud.dialogflow_v2.types.DeleteAgentRequest, dict]): + The request object. The request message for + [Agents.DeleteAgent][google.cloud.dialogflow.v2.Agents.DeleteAgent]. + parent (:class:`str`): + Required. The project that the agent to delete is + associated with. Format: ``projects/``. + + 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. + """ + # 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 = agent.DeleteAgentRequest(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.delete_agent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def search_agents(self, + request: Union[agent.SearchAgentsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAgentsAsyncPager: + r"""Returns the list of agents. + + Since there is at most one conversational agent per project, + this method is useful primarily for listing all agents across + projects the caller has access to. One can achieve that with a + wildcard project collection id "-". Refer to `List + Sub-Collections `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.SearchAgentsRequest, dict]): + The request object. The request message for + [Agents.SearchAgents][google.cloud.dialogflow.v2.Agents.SearchAgents]. + parent (:class:`str`): + Required. The project to list agents from. Format: + ``projects/``. + + 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.dialogflow_v2.services.agents.pagers.SearchAgentsAsyncPager: + The response message for + [Agents.SearchAgents][google.cloud.dialogflow.v2.Agents.SearchAgents]. + + 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 = agent.SearchAgentsRequest(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.search_agents, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.SearchAgentsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def train_agent(self, + request: Union[agent.TrainAgentRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Trains the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.TrainAgentRequest, dict]): + The request object. The request message for + [Agents.TrainAgent][google.cloud.dialogflow.v2.Agents.TrainAgent]. + parent (:class:`str`): + Required. The project that the agent to train is + associated with. Format: ``projects/``. + + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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 = agent.TrainAgentRequest(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.train_agent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def export_agent(self, + request: Union[agent.ExportAgentRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Exports the specified agent to a ZIP file. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ExportAgentResponse][google.cloud.dialogflow.v2.ExportAgentResponse] + + Args: + request (Union[google.cloud.dialogflow_v2.types.ExportAgentRequest, dict]): + The request object. The request message for + [Agents.ExportAgent][google.cloud.dialogflow.v2.Agents.ExportAgent]. + parent (:class:`str`): + Required. The project that the agent to export is + associated with. Format: ``projects/``. + + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflow_v2.types.ExportAgentResponse` + The response message for + [Agents.ExportAgent][google.cloud.dialogflow.v2.Agents.ExportAgent]. + + """ + # 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 = agent.ExportAgentRequest(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.export_agent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + agent.ExportAgentResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def import_agent(self, + request: Union[agent.ImportAgentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Imports the specified agent from a ZIP file. + + Uploads new intents and entity types without deleting the + existing ones. Intents and entity types with the same name are + replaced with the new versions from + [ImportAgentRequest][google.cloud.dialogflow.v2.ImportAgentRequest]. + After the import, the imported draft agent will be trained + automatically (unless disabled in agent settings). However, once + the import is done, training may not be completed yet. Please + call [TrainAgent][google.cloud.dialogflow.v2.Agents.TrainAgent] + and wait for the operation it returns in order to train + explicitly. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + The operation only tracks when importing is complete, not when + it is done training. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ImportAgentRequest, dict]): + The request object. The request message for + [Agents.ImportAgent][google.cloud.dialogflow.v2.Agents.ImportAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + request = agent.ImportAgentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_agent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def restore_agent(self, + request: Union[agent.RestoreAgentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Restores the specified agent from a ZIP file. + + Replaces the current agent version with a new one. All the + intents and entity types in the older version are deleted. After + the restore, the restored draft agent will be trained + automatically (unless disabled in agent settings). However, once + the restore is done, training may not be completed yet. Please + call [TrainAgent][google.cloud.dialogflow.v2.Agents.TrainAgent] + and wait for the operation it returns in order to train + explicitly. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + The operation only tracks when restoring is complete, not when + it is done training. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.RestoreAgentRequest, dict]): + The request object. The request message for + [Agents.RestoreAgent][google.cloud.dialogflow.v2.Agents.RestoreAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + request = agent.RestoreAgentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.restore_agent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def get_validation_result(self, + request: Union[agent.GetValidationResultRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> validation_result.ValidationResult: + r"""Gets agent validation result. Agent validation is + performed during training time and is updated + automatically when training is completed. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetValidationResultRequest, dict]): + The request object. The request message for + [Agents.GetValidationResult][google.cloud.dialogflow.v2.Agents.GetValidationResult]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.ValidationResult: + Represents the output of agent + validation. + + """ + # Create or coerce a protobuf request object. + request = agent.GetValidationResultRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_validation_result, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "AgentsAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/client.py new file mode 100644 index 000000000..03ffd5b58 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/client.py @@ -0,0 +1,1176 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.dialogflow_v2.services.agents import pagers +from google.cloud.dialogflow_v2.types import agent +from google.cloud.dialogflow_v2.types import agent as gcd_agent +from google.cloud.dialogflow_v2.types import validation_result +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import AgentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AgentsGrpcTransport +from .transports.grpc_asyncio import AgentsGrpcAsyncIOTransport + + +class AgentsClientMeta(type): + """Metaclass for the Agents 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[AgentsTransport]] + _transport_registry["grpc"] = AgentsGrpcTransport + _transport_registry["grpc_asyncio"] = AgentsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[AgentsTransport]: + """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 AgentsClient(metaclass=AgentsClientMeta): + """Service for managing [Agents][google.cloud.dialogflow.v2.Agent].""" + + @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 = "dialogflow.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: + AgentsClient: 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: + AgentsClient: 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) -> AgentsTransport: + """Returns the transport used by the client instance. + + Returns: + AgentsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def agent_path(project: str,) -> str: + """Returns a fully-qualified agent string.""" + return "projects/{project}/agent".format(project=project, ) + + @staticmethod + def parse_agent_path(path: str) -> Dict[str,str]: + """Parses a agent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent$", 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, AgentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the agents 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, AgentsTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, AgentsTransport): + # transport is a AgentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def get_agent(self, + request: Union[agent.GetAgentRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> agent.Agent: + r"""Retrieves the specified agent. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetAgentRequest, dict]): + The request object. The request message for + [Agents.GetAgent][google.cloud.dialogflow.v2.Agents.GetAgent]. + parent (str): + Required. The project that the agent to fetch is + associated with. Format: ``projects/``. + + 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.dialogflow_v2.types.Agent: + A Dialogflow agent is a virtual agent that handles conversations with your + end-users. It is a natural language understanding + module that understands the nuances of human + language. Dialogflow translates end-user text or + audio during a conversation to structured data that + your apps and services can understand. You design and + build a Dialogflow agent to handle the types of + conversations required for your system. + + For more information about agents, see the [Agent + guide](\ https://cloud.google.com/dialogflow/docs/agents-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is 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 agent.GetAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.GetAgentRequest): + request = agent.GetAgentRequest(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.get_agent] + + # Certain 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 set_agent(self, + request: Union[gcd_agent.SetAgentRequest, dict] = None, + *, + agent: gcd_agent.Agent = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_agent.Agent: + r"""Creates/updates the specified agent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.SetAgentRequest, dict]): + The request object. The request message for + [Agents.SetAgent][google.cloud.dialogflow.v2.Agents.SetAgent]. + agent (google.cloud.dialogflow_v2.types.Agent): + Required. The agent to update. + This corresponds to the ``agent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Agent: + A Dialogflow agent is a virtual agent that handles conversations with your + end-users. It is a natural language understanding + module that understands the nuances of human + language. Dialogflow translates end-user text or + audio during a conversation to structured data that + your apps and services can understand. You design and + build a Dialogflow agent to handle the types of + conversations required for your system. + + For more information about agents, see the [Agent + guide](\ https://cloud.google.com/dialogflow/docs/agents-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([agent]) + if request is 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 gcd_agent.SetAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_agent.SetAgentRequest): + request = gcd_agent.SetAgentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if agent is not None: + request.agent = agent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_agent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("agent.parent", request.agent.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_agent(self, + request: Union[agent.DeleteAgentRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified agent. + + Args: + request (Union[google.cloud.dialogflow_v2.types.DeleteAgentRequest, dict]): + The request object. The request message for + [Agents.DeleteAgent][google.cloud.dialogflow.v2.Agents.DeleteAgent]. + parent (str): + Required. The project that the agent to delete is + associated with. Format: ``projects/``. + + 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. + """ + # 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 agent.DeleteAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.DeleteAgentRequest): + request = agent.DeleteAgentRequest(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.delete_agent] + + # Certain 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. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def search_agents(self, + request: Union[agent.SearchAgentsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAgentsPager: + r"""Returns the list of agents. + + Since there is at most one conversational agent per project, + this method is useful primarily for listing all agents across + projects the caller has access to. One can achieve that with a + wildcard project collection id "-". Refer to `List + Sub-Collections `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.SearchAgentsRequest, dict]): + The request object. The request message for + [Agents.SearchAgents][google.cloud.dialogflow.v2.Agents.SearchAgents]. + parent (str): + Required. The project to list agents from. Format: + ``projects/``. + + 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.dialogflow_v2.services.agents.pagers.SearchAgentsPager: + The response message for + [Agents.SearchAgents][google.cloud.dialogflow.v2.Agents.SearchAgents]. + + 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 agent.SearchAgentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.SearchAgentsRequest): + request = agent.SearchAgentsRequest(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.search_agents] + + # Certain 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.SearchAgentsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def train_agent(self, + request: Union[agent.TrainAgentRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Trains the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.TrainAgentRequest, dict]): + The request object. The request message for + [Agents.TrainAgent][google.cloud.dialogflow.v2.Agents.TrainAgent]. + parent (str): + Required. The project that the agent to train is + associated with. Format: ``projects/``. + + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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 agent.TrainAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.TrainAgentRequest): + request = agent.TrainAgentRequest(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.train_agent] + + # Certain 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, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def export_agent(self, + request: Union[agent.ExportAgentRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Exports the specified agent to a ZIP file. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ExportAgentResponse][google.cloud.dialogflow.v2.ExportAgentResponse] + + Args: + request (Union[google.cloud.dialogflow_v2.types.ExportAgentRequest, dict]): + The request object. The request message for + [Agents.ExportAgent][google.cloud.dialogflow.v2.Agents.ExportAgent]. + parent (str): + Required. The project that the agent to export is + associated with. Format: ``projects/``. + + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflow_v2.types.ExportAgentResponse` + The response message for + [Agents.ExportAgent][google.cloud.dialogflow.v2.Agents.ExportAgent]. + + """ + # 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 agent.ExportAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.ExportAgentRequest): + request = agent.ExportAgentRequest(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.export_agent] + + # Certain 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, + agent.ExportAgentResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def import_agent(self, + request: Union[agent.ImportAgentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Imports the specified agent from a ZIP file. + + Uploads new intents and entity types without deleting the + existing ones. Intents and entity types with the same name are + replaced with the new versions from + [ImportAgentRequest][google.cloud.dialogflow.v2.ImportAgentRequest]. + After the import, the imported draft agent will be trained + automatically (unless disabled in agent settings). However, once + the import is done, training may not be completed yet. Please + call [TrainAgent][google.cloud.dialogflow.v2.Agents.TrainAgent] + and wait for the operation it returns in order to train + explicitly. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + The operation only tracks when importing is complete, not when + it is done training. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ImportAgentRequest, dict]): + The request object. The request message for + [Agents.ImportAgent][google.cloud.dialogflow.v2.Agents.ImportAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a agent.ImportAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.ImportAgentRequest): + request = agent.ImportAgentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_agent] + + # Certain 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, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def restore_agent(self, + request: Union[agent.RestoreAgentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Restores the specified agent from a ZIP file. + + Replaces the current agent version with a new one. All the + intents and entity types in the older version are deleted. After + the restore, the restored draft agent will be trained + automatically (unless disabled in agent settings). However, once + the restore is done, training may not be completed yet. Please + call [TrainAgent][google.cloud.dialogflow.v2.Agents.TrainAgent] + and wait for the operation it returns in order to train + explicitly. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + The operation only tracks when restoring is complete, not when + it is done training. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.RestoreAgentRequest, dict]): + The request object. The request message for + [Agents.RestoreAgent][google.cloud.dialogflow.v2.Agents.RestoreAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a agent.RestoreAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.RestoreAgentRequest): + request = agent.RestoreAgentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.restore_agent] + + # Certain 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, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def get_validation_result(self, + request: Union[agent.GetValidationResultRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> validation_result.ValidationResult: + r"""Gets agent validation result. Agent validation is + performed during training time and is updated + automatically when training is completed. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetValidationResultRequest, dict]): + The request object. The request message for + [Agents.GetValidationResult][google.cloud.dialogflow.v2.Agents.GetValidationResult]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.ValidationResult: + Represents the output of agent + validation. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a agent.GetValidationResultRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.GetValidationResultRequest): + request = agent.GetValidationResultRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_validation_result] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "AgentsClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/pagers.py new file mode 100644 index 000000000..81e85e516 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflow_v2.types import agent + + +class SearchAgentsPager: + """A pager for iterating through ``search_agents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.SearchAgentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``agents`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchAgents`` requests and continue to iterate + through the ``agents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.SearchAgentsResponse` + 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[..., agent.SearchAgentsResponse], + request: agent.SearchAgentsRequest, + response: agent.SearchAgentsResponse, + *, + 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.dialogflow_v2.types.SearchAgentsRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.SearchAgentsResponse): + 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 = agent.SearchAgentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[agent.SearchAgentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[agent.Agent]: + for page in self.pages: + yield from page.agents + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchAgentsAsyncPager: + """A pager for iterating through ``search_agents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.SearchAgentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``agents`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchAgents`` requests and continue to iterate + through the ``agents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.SearchAgentsResponse` + 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[agent.SearchAgentsResponse]], + request: agent.SearchAgentsRequest, + response: agent.SearchAgentsResponse, + *, + 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.dialogflow_v2.types.SearchAgentsRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.SearchAgentsResponse): + 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 = agent.SearchAgentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[agent.SearchAgentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[agent.Agent]: + async def async_generator(): + async for page in self.pages: + for response in page.agents: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/__init__.py new file mode 100644 index 000000000..0dc0c06c1 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/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 AgentsTransport +from .grpc import AgentsGrpcTransport +from .grpc_asyncio import AgentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AgentsTransport]] +_transport_registry['grpc'] = AgentsGrpcTransport +_transport_registry['grpc_asyncio'] = AgentsGrpcAsyncIOTransport + +__all__ = ( + 'AgentsTransport', + 'AgentsGrpcTransport', + 'AgentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/base.py new file mode 100644 index 000000000..ead68940a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.types import agent +from google.cloud.dialogflow_v2.types import agent as gcd_agent +from google.cloud.dialogflow_v2.types import validation_result +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-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class AgentsTransport(abc.ABC): + """Abstract transport class for Agents.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_agent: gapic_v1.method.wrap_method( + self.get_agent, + default_timeout=None, + client_info=client_info, + ), + self.set_agent: gapic_v1.method.wrap_method( + self.set_agent, + default_timeout=None, + client_info=client_info, + ), + self.delete_agent: gapic_v1.method.wrap_method( + self.delete_agent, + default_timeout=None, + client_info=client_info, + ), + self.search_agents: gapic_v1.method.wrap_method( + self.search_agents, + default_timeout=None, + client_info=client_info, + ), + self.train_agent: gapic_v1.method.wrap_method( + self.train_agent, + default_timeout=None, + client_info=client_info, + ), + self.export_agent: gapic_v1.method.wrap_method( + self.export_agent, + default_timeout=None, + client_info=client_info, + ), + self.import_agent: gapic_v1.method.wrap_method( + self.import_agent, + default_timeout=None, + client_info=client_info, + ), + self.restore_agent: gapic_v1.method.wrap_method( + self.restore_agent, + default_timeout=None, + client_info=client_info, + ), + self.get_validation_result: gapic_v1.method.wrap_method( + self.get_validation_result, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def get_agent(self) -> Callable[ + [agent.GetAgentRequest], + Union[ + agent.Agent, + Awaitable[agent.Agent] + ]]: + raise NotImplementedError() + + @property + def set_agent(self) -> Callable[ + [gcd_agent.SetAgentRequest], + Union[ + gcd_agent.Agent, + Awaitable[gcd_agent.Agent] + ]]: + raise NotImplementedError() + + @property + def delete_agent(self) -> Callable[ + [agent.DeleteAgentRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def search_agents(self) -> Callable[ + [agent.SearchAgentsRequest], + Union[ + agent.SearchAgentsResponse, + Awaitable[agent.SearchAgentsResponse] + ]]: + raise NotImplementedError() + + @property + def train_agent(self) -> Callable[ + [agent.TrainAgentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def export_agent(self) -> Callable[ + [agent.ExportAgentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def import_agent(self) -> Callable[ + [agent.ImportAgentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def restore_agent(self) -> Callable[ + [agent.RestoreAgentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_validation_result(self) -> Callable[ + [agent.GetValidationResultRequest], + Union[ + validation_result.ValidationResult, + Awaitable[validation_result.ValidationResult] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'AgentsTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/grpc.py new file mode 100644 index 000000000..e399398ac --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/grpc.py @@ -0,0 +1,574 @@ +# -*- 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 +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import agent +from google.cloud.dialogflow_v2.types import agent as gcd_agent +from google.cloud.dialogflow_v2.types import validation_result +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import AgentsTransport, DEFAULT_CLIENT_INFO + + +class AgentsGrpcTransport(AgentsTransport): + """gRPC backend transport for Agents. + + Service for managing [Agents][google.cloud.dialogflow.v2.Agent]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 = 'dialogflow.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 get_agent(self) -> Callable[ + [agent.GetAgentRequest], + agent.Agent]: + r"""Return a callable for the get agent method over gRPC. + + Retrieves the specified agent. + + Returns: + Callable[[~.GetAgentRequest], + ~.Agent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_agent' not in self._stubs: + self._stubs['get_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Agents/GetAgent', + request_serializer=agent.GetAgentRequest.serialize, + response_deserializer=agent.Agent.deserialize, + ) + return self._stubs['get_agent'] + + @property + def set_agent(self) -> Callable[ + [gcd_agent.SetAgentRequest], + gcd_agent.Agent]: + r"""Return a callable for the set agent method over gRPC. + + Creates/updates the specified agent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.SetAgentRequest], + ~.Agent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_agent' not in self._stubs: + self._stubs['set_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Agents/SetAgent', + request_serializer=gcd_agent.SetAgentRequest.serialize, + response_deserializer=gcd_agent.Agent.deserialize, + ) + return self._stubs['set_agent'] + + @property + def delete_agent(self) -> Callable[ + [agent.DeleteAgentRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete agent method over gRPC. + + Deletes the specified agent. + + Returns: + Callable[[~.DeleteAgentRequest], + ~.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_agent' not in self._stubs: + self._stubs['delete_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Agents/DeleteAgent', + request_serializer=agent.DeleteAgentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_agent'] + + @property + def search_agents(self) -> Callable[ + [agent.SearchAgentsRequest], + agent.SearchAgentsResponse]: + r"""Return a callable for the search agents method over gRPC. + + Returns the list of agents. + + Since there is at most one conversational agent per project, + this method is useful primarily for listing all agents across + projects the caller has access to. One can achieve that with a + wildcard project collection id "-". Refer to `List + Sub-Collections `__. + + Returns: + Callable[[~.SearchAgentsRequest], + ~.SearchAgentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_agents' not in self._stubs: + self._stubs['search_agents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Agents/SearchAgents', + request_serializer=agent.SearchAgentsRequest.serialize, + response_deserializer=agent.SearchAgentsResponse.deserialize, + ) + return self._stubs['search_agents'] + + @property + def train_agent(self) -> Callable[ + [agent.TrainAgentRequest], + operations_pb2.Operation]: + r"""Return a callable for the train agent method over gRPC. + + Trains the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.TrainAgentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'train_agent' not in self._stubs: + self._stubs['train_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Agents/TrainAgent', + request_serializer=agent.TrainAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['train_agent'] + + @property + def export_agent(self) -> Callable[ + [agent.ExportAgentRequest], + operations_pb2.Operation]: + r"""Return a callable for the export agent method over gRPC. + + Exports the specified agent to a ZIP file. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ExportAgentResponse][google.cloud.dialogflow.v2.ExportAgentResponse] + + Returns: + Callable[[~.ExportAgentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'export_agent' not in self._stubs: + self._stubs['export_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Agents/ExportAgent', + request_serializer=agent.ExportAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_agent'] + + @property + def import_agent(self) -> Callable[ + [agent.ImportAgentRequest], + operations_pb2.Operation]: + r"""Return a callable for the import agent method over gRPC. + + Imports the specified agent from a ZIP file. + + Uploads new intents and entity types without deleting the + existing ones. Intents and entity types with the same name are + replaced with the new versions from + [ImportAgentRequest][google.cloud.dialogflow.v2.ImportAgentRequest]. + After the import, the imported draft agent will be trained + automatically (unless disabled in agent settings). However, once + the import is done, training may not be completed yet. Please + call [TrainAgent][google.cloud.dialogflow.v2.Agents.TrainAgent] + and wait for the operation it returns in order to train + explicitly. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + The operation only tracks when importing is complete, not when + it is done training. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.ImportAgentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_agent' not in self._stubs: + self._stubs['import_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Agents/ImportAgent', + request_serializer=agent.ImportAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_agent'] + + @property + def restore_agent(self) -> Callable[ + [agent.RestoreAgentRequest], + operations_pb2.Operation]: + r"""Return a callable for the restore agent method over gRPC. + + Restores the specified agent from a ZIP file. + + Replaces the current agent version with a new one. All the + intents and entity types in the older version are deleted. After + the restore, the restored draft agent will be trained + automatically (unless disabled in agent settings). However, once + the restore is done, training may not be completed yet. Please + call [TrainAgent][google.cloud.dialogflow.v2.Agents.TrainAgent] + and wait for the operation it returns in order to train + explicitly. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + The operation only tracks when restoring is complete, not when + it is done training. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.RestoreAgentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'restore_agent' not in self._stubs: + self._stubs['restore_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Agents/RestoreAgent', + request_serializer=agent.RestoreAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restore_agent'] + + @property + def get_validation_result(self) -> Callable[ + [agent.GetValidationResultRequest], + validation_result.ValidationResult]: + r"""Return a callable for the get validation result method over gRPC. + + Gets agent validation result. Agent validation is + performed during training time and is updated + automatically when training is completed. + + Returns: + Callable[[~.GetValidationResultRequest], + ~.ValidationResult]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_validation_result' not in self._stubs: + self._stubs['get_validation_result'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Agents/GetValidationResult', + request_serializer=agent.GetValidationResultRequest.serialize, + response_deserializer=validation_result.ValidationResult.deserialize, + ) + return self._stubs['get_validation_result'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'AgentsGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/grpc_asyncio.py new file mode 100644 index 000000000..8b4689eb2 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/grpc_asyncio.py @@ -0,0 +1,578 @@ +# -*- 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 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import agent +from google.cloud.dialogflow_v2.types import agent as gcd_agent +from google.cloud.dialogflow_v2.types import validation_result +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import AgentsTransport, DEFAULT_CLIENT_INFO +from .grpc import AgentsGrpcTransport + + +class AgentsGrpcAsyncIOTransport(AgentsTransport): + """gRPC AsyncIO backend transport for Agents. + + Service for managing [Agents][google.cloud.dialogflow.v2.Agent]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 get_agent(self) -> Callable[ + [agent.GetAgentRequest], + Awaitable[agent.Agent]]: + r"""Return a callable for the get agent method over gRPC. + + Retrieves the specified agent. + + Returns: + Callable[[~.GetAgentRequest], + Awaitable[~.Agent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_agent' not in self._stubs: + self._stubs['get_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Agents/GetAgent', + request_serializer=agent.GetAgentRequest.serialize, + response_deserializer=agent.Agent.deserialize, + ) + return self._stubs['get_agent'] + + @property + def set_agent(self) -> Callable[ + [gcd_agent.SetAgentRequest], + Awaitable[gcd_agent.Agent]]: + r"""Return a callable for the set agent method over gRPC. + + Creates/updates the specified agent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.SetAgentRequest], + Awaitable[~.Agent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_agent' not in self._stubs: + self._stubs['set_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Agents/SetAgent', + request_serializer=gcd_agent.SetAgentRequest.serialize, + response_deserializer=gcd_agent.Agent.deserialize, + ) + return self._stubs['set_agent'] + + @property + def delete_agent(self) -> Callable[ + [agent.DeleteAgentRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete agent method over gRPC. + + Deletes the specified agent. + + Returns: + Callable[[~.DeleteAgentRequest], + 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_agent' not in self._stubs: + self._stubs['delete_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Agents/DeleteAgent', + request_serializer=agent.DeleteAgentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_agent'] + + @property + def search_agents(self) -> Callable[ + [agent.SearchAgentsRequest], + Awaitable[agent.SearchAgentsResponse]]: + r"""Return a callable for the search agents method over gRPC. + + Returns the list of agents. + + Since there is at most one conversational agent per project, + this method is useful primarily for listing all agents across + projects the caller has access to. One can achieve that with a + wildcard project collection id "-". Refer to `List + Sub-Collections `__. + + Returns: + Callable[[~.SearchAgentsRequest], + Awaitable[~.SearchAgentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_agents' not in self._stubs: + self._stubs['search_agents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Agents/SearchAgents', + request_serializer=agent.SearchAgentsRequest.serialize, + response_deserializer=agent.SearchAgentsResponse.deserialize, + ) + return self._stubs['search_agents'] + + @property + def train_agent(self) -> Callable[ + [agent.TrainAgentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the train agent method over gRPC. + + Trains the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.TrainAgentRequest], + 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 'train_agent' not in self._stubs: + self._stubs['train_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Agents/TrainAgent', + request_serializer=agent.TrainAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['train_agent'] + + @property + def export_agent(self) -> Callable[ + [agent.ExportAgentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the export agent method over gRPC. + + Exports the specified agent to a ZIP file. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ExportAgentResponse][google.cloud.dialogflow.v2.ExportAgentResponse] + + Returns: + Callable[[~.ExportAgentRequest], + 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 'export_agent' not in self._stubs: + self._stubs['export_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Agents/ExportAgent', + request_serializer=agent.ExportAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_agent'] + + @property + def import_agent(self) -> Callable[ + [agent.ImportAgentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import agent method over gRPC. + + Imports the specified agent from a ZIP file. + + Uploads new intents and entity types without deleting the + existing ones. Intents and entity types with the same name are + replaced with the new versions from + [ImportAgentRequest][google.cloud.dialogflow.v2.ImportAgentRequest]. + After the import, the imported draft agent will be trained + automatically (unless disabled in agent settings). However, once + the import is done, training may not be completed yet. Please + call [TrainAgent][google.cloud.dialogflow.v2.Agents.TrainAgent] + and wait for the operation it returns in order to train + explicitly. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + The operation only tracks when importing is complete, not when + it is done training. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.ImportAgentRequest], + 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_agent' not in self._stubs: + self._stubs['import_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Agents/ImportAgent', + request_serializer=agent.ImportAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_agent'] + + @property + def restore_agent(self) -> Callable[ + [agent.RestoreAgentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the restore agent method over gRPC. + + Restores the specified agent from a ZIP file. + + Replaces the current agent version with a new one. All the + intents and entity types in the older version are deleted. After + the restore, the restored draft agent will be trained + automatically (unless disabled in agent settings). However, once + the restore is done, training may not be completed yet. Please + call [TrainAgent][google.cloud.dialogflow.v2.Agents.TrainAgent] + and wait for the operation it returns in order to train + explicitly. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + The operation only tracks when restoring is complete, not when + it is done training. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.RestoreAgentRequest], + 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 'restore_agent' not in self._stubs: + self._stubs['restore_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Agents/RestoreAgent', + request_serializer=agent.RestoreAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restore_agent'] + + @property + def get_validation_result(self) -> Callable[ + [agent.GetValidationResultRequest], + Awaitable[validation_result.ValidationResult]]: + r"""Return a callable for the get validation result method over gRPC. + + Gets agent validation result. Agent validation is + performed during training time and is updated + automatically when training is completed. + + Returns: + Callable[[~.GetValidationResultRequest], + Awaitable[~.ValidationResult]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_validation_result' not in self._stubs: + self._stubs['get_validation_result'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Agents/GetValidationResult', + request_serializer=agent.GetValidationResultRequest.serialize, + response_deserializer=validation_result.ValidationResult.deserialize, + ) + return self._stubs['get_validation_result'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'AgentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/__init__.py new file mode 100644 index 000000000..16c67859b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/__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 AnswerRecordsClient +from .async_client import AnswerRecordsAsyncClient + +__all__ = ( + 'AnswerRecordsClient', + 'AnswerRecordsAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/async_client.py new file mode 100644 index 000000000..91ccf57f0 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/async_client.py @@ -0,0 +1,377 @@ +# -*- 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 + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2.services.answer_records import pagers +from google.cloud.dialogflow_v2.types import answer_record +from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AnswerRecordsGrpcAsyncIOTransport +from .client import AnswerRecordsClient + + +class AnswerRecordsAsyncClient: + """Service for managing + [AnswerRecords][google.cloud.dialogflow.v2.AnswerRecord]. + """ + + _client: AnswerRecordsClient + + DEFAULT_ENDPOINT = AnswerRecordsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AnswerRecordsClient.DEFAULT_MTLS_ENDPOINT + + answer_record_path = staticmethod(AnswerRecordsClient.answer_record_path) + parse_answer_record_path = staticmethod(AnswerRecordsClient.parse_answer_record_path) + common_billing_account_path = staticmethod(AnswerRecordsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AnswerRecordsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AnswerRecordsClient.common_folder_path) + parse_common_folder_path = staticmethod(AnswerRecordsClient.parse_common_folder_path) + common_organization_path = staticmethod(AnswerRecordsClient.common_organization_path) + parse_common_organization_path = staticmethod(AnswerRecordsClient.parse_common_organization_path) + common_project_path = staticmethod(AnswerRecordsClient.common_project_path) + parse_common_project_path = staticmethod(AnswerRecordsClient.parse_common_project_path) + common_location_path = staticmethod(AnswerRecordsClient.common_location_path) + parse_common_location_path = staticmethod(AnswerRecordsClient.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: + AnswerRecordsAsyncClient: The constructed client. + """ + return AnswerRecordsClient.from_service_account_info.__func__(AnswerRecordsAsyncClient, 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: + AnswerRecordsAsyncClient: The constructed client. + """ + return AnswerRecordsClient.from_service_account_file.__func__(AnswerRecordsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> AnswerRecordsTransport: + """Returns the transport used by the client instance. + + Returns: + AnswerRecordsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(AnswerRecordsClient).get_transport_class, type(AnswerRecordsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, AnswerRecordsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the answer records 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, ~.AnswerRecordsTransport]): 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 = AnswerRecordsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_answer_records(self, + request: Union[answer_record.ListAnswerRecordsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAnswerRecordsAsyncPager: + r"""Returns the list of all answer records in the + specified project in reverse chronological order. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListAnswerRecordsRequest, dict]): + The request object. Request message for + [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. + parent (:class:`str`): + Required. The project to list all answer records for in + reverse chronological order. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.services.answer_records.pagers.ListAnswerRecordsAsyncPager: + Response message for + [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. + + 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 = answer_record.ListAnswerRecordsRequest(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_answer_records, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAnswerRecordsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_answer_record(self, + request: Union[gcd_answer_record.UpdateAnswerRecordRequest, dict] = None, + *, + answer_record: gcd_answer_record.AnswerRecord = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_answer_record.AnswerRecord: + r"""Updates the specified answer record. + + Args: + request (Union[google.cloud.dialogflow_v2.types.UpdateAnswerRecordRequest, dict]): + The request object. Request message for + [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2.AnswerRecords.UpdateAnswerRecord]. + answer_record (:class:`google.cloud.dialogflow_v2.types.AnswerRecord`): + Required. Answer record to update. + This corresponds to the ``answer_record`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.AnswerRecord: + Answer records are records to manage answer history and feedbacks for + Dialogflow. + + Currently, answer record includes: + + - human agent assistant article suggestion + - human agent assistant faq article + + It doesn't include: + + - DetectIntent intent matching + - DetectIntent knowledge + + Answer records are not related to the conversation + history in the Dialogflow Console. A Record is + generated even when the end-user disables + conversation history in the console. Records are + created when there's a human agent assistant + suggestion generated. + + A typical workflow for customers provide feedback to + an answer is: + + 1. For human agent assistant, customers get + suggestion via ListSuggestions API. Together with + the answers, + [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] + are returned to the customers. + 2. The customer uses the + [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] + to call the [UpdateAnswerRecord][] method to send + feedback about a specific answer that they believe + is wrong. + + """ + # 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([answer_record, 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 = gcd_answer_record.UpdateAnswerRecordRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if answer_record is not None: + request.answer_record = answer_record + 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_answer_record, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("answer_record.name", request.answer_record.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "AnswerRecordsAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/client.py new file mode 100644 index 000000000..a0c35b43a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/client.py @@ -0,0 +1,575 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2.services.answer_records import pagers +from google.cloud.dialogflow_v2.types import answer_record +from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AnswerRecordsGrpcTransport +from .transports.grpc_asyncio import AnswerRecordsGrpcAsyncIOTransport + + +class AnswerRecordsClientMeta(type): + """Metaclass for the AnswerRecords 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[AnswerRecordsTransport]] + _transport_registry["grpc"] = AnswerRecordsGrpcTransport + _transport_registry["grpc_asyncio"] = AnswerRecordsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[AnswerRecordsTransport]: + """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 AnswerRecordsClient(metaclass=AnswerRecordsClientMeta): + """Service for managing + [AnswerRecords][google.cloud.dialogflow.v2.AnswerRecord]. + """ + + @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 = "dialogflow.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: + AnswerRecordsClient: 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: + AnswerRecordsClient: 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) -> AnswerRecordsTransport: + """Returns the transport used by the client instance. + + Returns: + AnswerRecordsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def answer_record_path(project: str,answer_record: str,) -> str: + """Returns a fully-qualified answer_record string.""" + return "projects/{project}/answerRecords/{answer_record}".format(project=project, answer_record=answer_record, ) + + @staticmethod + def parse_answer_record_path(path: str) -> Dict[str,str]: + """Parses a answer_record path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/answerRecords/(?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, AnswerRecordsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the answer records 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, AnswerRecordsTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, AnswerRecordsTransport): + # transport is a AnswerRecordsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_answer_records(self, + request: Union[answer_record.ListAnswerRecordsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAnswerRecordsPager: + r"""Returns the list of all answer records in the + specified project in reverse chronological order. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListAnswerRecordsRequest, dict]): + The request object. Request message for + [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. + parent (str): + Required. The project to list all answer records for in + reverse chronological order. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.services.answer_records.pagers.ListAnswerRecordsPager: + Response message for + [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. + + 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 answer_record.ListAnswerRecordsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, answer_record.ListAnswerRecordsRequest): + request = answer_record.ListAnswerRecordsRequest(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_answer_records] + + # Certain 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.ListAnswerRecordsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_answer_record(self, + request: Union[gcd_answer_record.UpdateAnswerRecordRequest, dict] = None, + *, + answer_record: gcd_answer_record.AnswerRecord = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_answer_record.AnswerRecord: + r"""Updates the specified answer record. + + Args: + request (Union[google.cloud.dialogflow_v2.types.UpdateAnswerRecordRequest, dict]): + The request object. Request message for + [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2.AnswerRecords.UpdateAnswerRecord]. + answer_record (google.cloud.dialogflow_v2.types.AnswerRecord): + Required. Answer record to update. + This corresponds to the ``answer_record`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.AnswerRecord: + Answer records are records to manage answer history and feedbacks for + Dialogflow. + + Currently, answer record includes: + + - human agent assistant article suggestion + - human agent assistant faq article + + It doesn't include: + + - DetectIntent intent matching + - DetectIntent knowledge + + Answer records are not related to the conversation + history in the Dialogflow Console. A Record is + generated even when the end-user disables + conversation history in the console. Records are + created when there's a human agent assistant + suggestion generated. + + A typical workflow for customers provide feedback to + an answer is: + + 1. For human agent assistant, customers get + suggestion via ListSuggestions API. Together with + the answers, + [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] + are returned to the customers. + 2. The customer uses the + [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] + to call the [UpdateAnswerRecord][] method to send + feedback about a specific answer that they believe + is wrong. + + """ + # 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([answer_record, 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 gcd_answer_record.UpdateAnswerRecordRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_answer_record.UpdateAnswerRecordRequest): + request = gcd_answer_record.UpdateAnswerRecordRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if answer_record is not None: + request.answer_record = answer_record + 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_answer_record] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("answer_record.name", request.answer_record.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "AnswerRecordsClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/pagers.py new file mode 100644 index 000000000..3a5e81e2d --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflow_v2.types import answer_record + + +class ListAnswerRecordsPager: + """A pager for iterating through ``list_answer_records`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListAnswerRecordsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``answer_records`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAnswerRecords`` requests and continue to iterate + through the ``answer_records`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListAnswerRecordsResponse` + 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[..., answer_record.ListAnswerRecordsResponse], + request: answer_record.ListAnswerRecordsRequest, + response: answer_record.ListAnswerRecordsResponse, + *, + 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.dialogflow_v2.types.ListAnswerRecordsRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListAnswerRecordsResponse): + 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 = answer_record.ListAnswerRecordsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[answer_record.ListAnswerRecordsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[answer_record.AnswerRecord]: + for page in self.pages: + yield from page.answer_records + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAnswerRecordsAsyncPager: + """A pager for iterating through ``list_answer_records`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListAnswerRecordsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``answer_records`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAnswerRecords`` requests and continue to iterate + through the ``answer_records`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListAnswerRecordsResponse` + 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[answer_record.ListAnswerRecordsResponse]], + request: answer_record.ListAnswerRecordsRequest, + response: answer_record.ListAnswerRecordsResponse, + *, + 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.dialogflow_v2.types.ListAnswerRecordsRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListAnswerRecordsResponse): + 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 = answer_record.ListAnswerRecordsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[answer_record.ListAnswerRecordsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[answer_record.AnswerRecord]: + async def async_generator(): + async for page in self.pages: + for response in page.answer_records: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/__init__.py new file mode 100644 index 000000000..99c08cf37 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/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 AnswerRecordsTransport +from .grpc import AnswerRecordsGrpcTransport +from .grpc_asyncio import AnswerRecordsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AnswerRecordsTransport]] +_transport_registry['grpc'] = AnswerRecordsGrpcTransport +_transport_registry['grpc_asyncio'] = AnswerRecordsGrpcAsyncIOTransport + +__all__ = ( + 'AnswerRecordsTransport', + 'AnswerRecordsGrpcTransport', + 'AnswerRecordsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/base.py new file mode 100644 index 000000000..dce724d1a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/base.py @@ -0,0 +1,162 @@ +# -*- 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.types import answer_record +from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class AnswerRecordsTransport(abc.ABC): + """Abstract transport class for AnswerRecords.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_answer_records: gapic_v1.method.wrap_method( + self.list_answer_records, + default_timeout=None, + client_info=client_info, + ), + self.update_answer_record: gapic_v1.method.wrap_method( + self.update_answer_record, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_answer_records(self) -> Callable[ + [answer_record.ListAnswerRecordsRequest], + Union[ + answer_record.ListAnswerRecordsResponse, + Awaitable[answer_record.ListAnswerRecordsResponse] + ]]: + raise NotImplementedError() + + @property + def update_answer_record(self) -> Callable[ + [gcd_answer_record.UpdateAnswerRecordRequest], + Union[ + gcd_answer_record.AnswerRecord, + Awaitable[gcd_answer_record.AnswerRecord] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'AnswerRecordsTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/grpc.py new file mode 100644 index 000000000..8b0973319 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/grpc.py @@ -0,0 +1,283 @@ +# -*- 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 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import answer_record +from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record +from .base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO + + +class AnswerRecordsGrpcTransport(AnswerRecordsTransport): + """gRPC backend transport for AnswerRecords. + + Service for managing + [AnswerRecords][google.cloud.dialogflow.v2.AnswerRecord]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 = 'dialogflow.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 list_answer_records(self) -> Callable[ + [answer_record.ListAnswerRecordsRequest], + answer_record.ListAnswerRecordsResponse]: + r"""Return a callable for the list answer records method over gRPC. + + Returns the list of all answer records in the + specified project in reverse chronological order. + + Returns: + Callable[[~.ListAnswerRecordsRequest], + ~.ListAnswerRecordsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_answer_records' not in self._stubs: + self._stubs['list_answer_records'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.AnswerRecords/ListAnswerRecords', + request_serializer=answer_record.ListAnswerRecordsRequest.serialize, + response_deserializer=answer_record.ListAnswerRecordsResponse.deserialize, + ) + return self._stubs['list_answer_records'] + + @property + def update_answer_record(self) -> Callable[ + [gcd_answer_record.UpdateAnswerRecordRequest], + gcd_answer_record.AnswerRecord]: + r"""Return a callable for the update answer record method over gRPC. + + Updates the specified answer record. + + Returns: + Callable[[~.UpdateAnswerRecordRequest], + ~.AnswerRecord]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_answer_record' not in self._stubs: + self._stubs['update_answer_record'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.AnswerRecords/UpdateAnswerRecord', + request_serializer=gcd_answer_record.UpdateAnswerRecordRequest.serialize, + response_deserializer=gcd_answer_record.AnswerRecord.deserialize, + ) + return self._stubs['update_answer_record'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'AnswerRecordsGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/grpc_asyncio.py new file mode 100644 index 000000000..ad2138d74 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/grpc_asyncio.py @@ -0,0 +1,287 @@ +# -*- 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 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import answer_record +from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record +from .base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO +from .grpc import AnswerRecordsGrpcTransport + + +class AnswerRecordsGrpcAsyncIOTransport(AnswerRecordsTransport): + """gRPC AsyncIO backend transport for AnswerRecords. + + Service for managing + [AnswerRecords][google.cloud.dialogflow.v2.AnswerRecord]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 list_answer_records(self) -> Callable[ + [answer_record.ListAnswerRecordsRequest], + Awaitable[answer_record.ListAnswerRecordsResponse]]: + r"""Return a callable for the list answer records method over gRPC. + + Returns the list of all answer records in the + specified project in reverse chronological order. + + Returns: + Callable[[~.ListAnswerRecordsRequest], + Awaitable[~.ListAnswerRecordsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_answer_records' not in self._stubs: + self._stubs['list_answer_records'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.AnswerRecords/ListAnswerRecords', + request_serializer=answer_record.ListAnswerRecordsRequest.serialize, + response_deserializer=answer_record.ListAnswerRecordsResponse.deserialize, + ) + return self._stubs['list_answer_records'] + + @property + def update_answer_record(self) -> Callable[ + [gcd_answer_record.UpdateAnswerRecordRequest], + Awaitable[gcd_answer_record.AnswerRecord]]: + r"""Return a callable for the update answer record method over gRPC. + + Updates the specified answer record. + + Returns: + Callable[[~.UpdateAnswerRecordRequest], + Awaitable[~.AnswerRecord]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_answer_record' not in self._stubs: + self._stubs['update_answer_record'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.AnswerRecords/UpdateAnswerRecord', + request_serializer=gcd_answer_record.UpdateAnswerRecordRequest.serialize, + response_deserializer=gcd_answer_record.AnswerRecord.deserialize, + ) + return self._stubs['update_answer_record'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'AnswerRecordsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/__init__.py new file mode 100644 index 000000000..b0d60f297 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/__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 ContextsClient +from .async_client import ContextsAsyncClient + +__all__ = ( + 'ContextsClient', + 'ContextsAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/async_client.py new file mode 100644 index 000000000..48193d683 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/async_client.py @@ -0,0 +1,710 @@ +# -*- 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 + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2.services.contexts import pagers +from google.cloud.dialogflow_v2.types import context +from google.cloud.dialogflow_v2.types import context as gcd_context +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import ContextsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ContextsGrpcAsyncIOTransport +from .client import ContextsClient + + +class ContextsAsyncClient: + """Service for managing [Contexts][google.cloud.dialogflow.v2.Context].""" + + _client: ContextsClient + + DEFAULT_ENDPOINT = ContextsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ContextsClient.DEFAULT_MTLS_ENDPOINT + + context_path = staticmethod(ContextsClient.context_path) + parse_context_path = staticmethod(ContextsClient.parse_context_path) + common_billing_account_path = staticmethod(ContextsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ContextsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ContextsClient.common_folder_path) + parse_common_folder_path = staticmethod(ContextsClient.parse_common_folder_path) + common_organization_path = staticmethod(ContextsClient.common_organization_path) + parse_common_organization_path = staticmethod(ContextsClient.parse_common_organization_path) + common_project_path = staticmethod(ContextsClient.common_project_path) + parse_common_project_path = staticmethod(ContextsClient.parse_common_project_path) + common_location_path = staticmethod(ContextsClient.common_location_path) + parse_common_location_path = staticmethod(ContextsClient.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: + ContextsAsyncClient: The constructed client. + """ + return ContextsClient.from_service_account_info.__func__(ContextsAsyncClient, 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: + ContextsAsyncClient: The constructed client. + """ + return ContextsClient.from_service_account_file.__func__(ContextsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ContextsTransport: + """Returns the transport used by the client instance. + + Returns: + ContextsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ContextsClient).get_transport_class, type(ContextsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ContextsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the contexts 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, ~.ContextsTransport]): 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 = ContextsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_contexts(self, + request: Union[context.ListContextsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListContextsAsyncPager: + r"""Returns the list of all contexts in the specified + session. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListContextsRequest, dict]): + The request object. The request message for + [Contexts.ListContexts][google.cloud.dialogflow.v2.Contexts.ListContexts]. + parent (:class:`str`): + Required. The session to list all contexts from. Format: + ``projects//agent/sessions/`` or + ``projects//agent/environments//users//sessions/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. If ``User ID`` is not + specified, we assume default '-' user. + + 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.dialogflow_v2.services.contexts.pagers.ListContextsAsyncPager: + The response message for + [Contexts.ListContexts][google.cloud.dialogflow.v2.Contexts.ListContexts]. + + 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 = context.ListContextsRequest(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_contexts, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListContextsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_context(self, + request: Union[context.GetContextRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> context.Context: + r"""Retrieves the specified context. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetContextRequest, dict]): + The request object. The request message for + [Contexts.GetContext][google.cloud.dialogflow.v2.Contexts.GetContext]. + name (:class:`str`): + Required. The name of the context. Format: + ``projects//agent/sessions//contexts/`` + or + ``projects//agent/environments//users//sessions//contexts/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. If ``User ID`` is not + specified, we assume default '-' user. + + 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.dialogflow_v2.types.Context: + Dialogflow contexts are similar to natural language context. If a person says + to you "they are orange", you need context in order + to understand what "they" is referring to. Similarly, + for Dialogflow to handle an end-user expression like + that, it needs to be provided with context in order + to correctly match an intent. + + Using contexts, you can control the flow of a + conversation. You can configure contexts for an + intent by setting input and output contexts, which + are identified by string names. When an intent is + matched, any configured output contexts for that + intent become active. While any contexts are active, + Dialogflow is more likely to match intents that are + configured with input contexts that correspond to the + currently active contexts. + + For more information about context, see the [Contexts + guide](\ https://cloud.google.com/dialogflow/docs/contexts-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = context.GetContextRequest(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_context, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_context(self, + request: Union[gcd_context.CreateContextRequest, dict] = None, + *, + parent: str = None, + context: gcd_context.Context = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_context.Context: + r"""Creates a context. + If the specified context already exists, overrides the + context. + + Args: + request (Union[google.cloud.dialogflow_v2.types.CreateContextRequest, dict]): + The request object. The request message for + [Contexts.CreateContext][google.cloud.dialogflow.v2.Contexts.CreateContext]. + parent (:class:`str`): + Required. The session to create a context for. Format: + ``projects//agent/sessions/`` or + ``projects//agent/environments//users//sessions/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. If ``User ID`` is not + specified, we assume default '-' user. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + context (:class:`google.cloud.dialogflow_v2.types.Context`): + Required. The context to create. + This corresponds to the ``context`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Context: + Dialogflow contexts are similar to natural language context. If a person says + to you "they are orange", you need context in order + to understand what "they" is referring to. Similarly, + for Dialogflow to handle an end-user expression like + that, it needs to be provided with context in order + to correctly match an intent. + + Using contexts, you can control the flow of a + conversation. You can configure contexts for an + intent by setting input and output contexts, which + are identified by string names. When an intent is + matched, any configured output contexts for that + intent become active. While any contexts are active, + Dialogflow is more likely to match intents that are + configured with input contexts that correspond to the + currently active contexts. + + For more information about context, see the [Contexts + guide](\ https://cloud.google.com/dialogflow/docs/contexts-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, context]) + if request is 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 = gcd_context.CreateContextRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if context is not None: + request.context = context + + # 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_context, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_context(self, + request: Union[gcd_context.UpdateContextRequest, dict] = None, + *, + context: gcd_context.Context = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_context.Context: + r"""Updates the specified context. + + Args: + request (Union[google.cloud.dialogflow_v2.types.UpdateContextRequest, dict]): + The request object. The request message for + [Contexts.UpdateContext][google.cloud.dialogflow.v2.Contexts.UpdateContext]. + context (:class:`google.cloud.dialogflow_v2.types.Context`): + Required. The context to update. + This corresponds to the ``context`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Context: + Dialogflow contexts are similar to natural language context. If a person says + to you "they are orange", you need context in order + to understand what "they" is referring to. Similarly, + for Dialogflow to handle an end-user expression like + that, it needs to be provided with context in order + to correctly match an intent. + + Using contexts, you can control the flow of a + conversation. You can configure contexts for an + intent by setting input and output contexts, which + are identified by string names. When an intent is + matched, any configured output contexts for that + intent become active. While any contexts are active, + Dialogflow is more likely to match intents that are + configured with input contexts that correspond to the + currently active contexts. + + For more information about context, see the [Contexts + guide](\ https://cloud.google.com/dialogflow/docs/contexts-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([context, 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 = gcd_context.UpdateContextRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if context is not None: + request.context = context + 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_context, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("context.name", request.context.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_context(self, + request: Union[context.DeleteContextRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified context. + + Args: + request (Union[google.cloud.dialogflow_v2.types.DeleteContextRequest, dict]): + The request object. The request message for + [Contexts.DeleteContext][google.cloud.dialogflow.v2.Contexts.DeleteContext]. + name (:class:`str`): + Required. The name of the context to delete. Format: + ``projects//agent/sessions//contexts/`` + or + ``projects//agent/environments//users//sessions//contexts/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. If ``User ID`` is not + specified, we assume default '-' user. + + 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 = context.DeleteContextRequest(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_context, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def delete_all_contexts(self, + request: Union[context.DeleteAllContextsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes all active contexts in the specified session. + + Args: + request (Union[google.cloud.dialogflow_v2.types.DeleteAllContextsRequest, dict]): + The request object. The request message for + [Contexts.DeleteAllContexts][google.cloud.dialogflow.v2.Contexts.DeleteAllContexts]. + parent (:class:`str`): + Required. The name of the session to delete all contexts + from. Format: + ``projects//agent/sessions/`` or + ``projects//agent/environments//users//sessions/``. + If ``Environment ID`` is not specified we assume default + 'draft' environment. If ``User ID`` is not specified, we + assume default '-' user. + + 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. + """ + # 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 = context.DeleteAllContextsRequest(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.delete_all_contexts, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ContextsAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/client.py new file mode 100644 index 000000000..722108987 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/client.py @@ -0,0 +1,908 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2.services.contexts import pagers +from google.cloud.dialogflow_v2.types import context +from google.cloud.dialogflow_v2.types import context as gcd_context +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import ContextsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ContextsGrpcTransport +from .transports.grpc_asyncio import ContextsGrpcAsyncIOTransport + + +class ContextsClientMeta(type): + """Metaclass for the Contexts 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[ContextsTransport]] + _transport_registry["grpc"] = ContextsGrpcTransport + _transport_registry["grpc_asyncio"] = ContextsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ContextsTransport]: + """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 ContextsClient(metaclass=ContextsClientMeta): + """Service for managing [Contexts][google.cloud.dialogflow.v2.Context].""" + + @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 = "dialogflow.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: + ContextsClient: 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: + ContextsClient: 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) -> ContextsTransport: + """Returns the transport used by the client instance. + + Returns: + ContextsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def context_path(project: str,session: str,context: str,) -> str: + """Returns a fully-qualified context string.""" + return "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) + + @staticmethod + def parse_context_path(path: str) -> Dict[str,str]: + """Parses a context path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/contexts/(?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, ContextsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the contexts 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, ContextsTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, ContextsTransport): + # transport is a ContextsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_contexts(self, + request: Union[context.ListContextsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListContextsPager: + r"""Returns the list of all contexts in the specified + session. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListContextsRequest, dict]): + The request object. The request message for + [Contexts.ListContexts][google.cloud.dialogflow.v2.Contexts.ListContexts]. + parent (str): + Required. The session to list all contexts from. Format: + ``projects//agent/sessions/`` or + ``projects//agent/environments//users//sessions/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. If ``User ID`` is not + specified, we assume default '-' user. + + 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.dialogflow_v2.services.contexts.pagers.ListContextsPager: + The response message for + [Contexts.ListContexts][google.cloud.dialogflow.v2.Contexts.ListContexts]. + + 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 context.ListContextsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, context.ListContextsRequest): + request = context.ListContextsRequest(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_contexts] + + # Certain 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.ListContextsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_context(self, + request: Union[context.GetContextRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> context.Context: + r"""Retrieves the specified context. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetContextRequest, dict]): + The request object. The request message for + [Contexts.GetContext][google.cloud.dialogflow.v2.Contexts.GetContext]. + name (str): + Required. The name of the context. Format: + ``projects//agent/sessions//contexts/`` + or + ``projects//agent/environments//users//sessions//contexts/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. If ``User ID`` is not + specified, we assume default '-' user. + + 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.dialogflow_v2.types.Context: + Dialogflow contexts are similar to natural language context. If a person says + to you "they are orange", you need context in order + to understand what "they" is referring to. Similarly, + for Dialogflow to handle an end-user expression like + that, it needs to be provided with context in order + to correctly match an intent. + + Using contexts, you can control the flow of a + conversation. You can configure contexts for an + intent by setting input and output contexts, which + are identified by string names. When an intent is + matched, any configured output contexts for that + intent become active. While any contexts are active, + Dialogflow is more likely to match intents that are + configured with input contexts that correspond to the + currently active contexts. + + For more information about context, see the [Contexts + guide](\ https://cloud.google.com/dialogflow/docs/contexts-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a context.GetContextRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, context.GetContextRequest): + request = context.GetContextRequest(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_context] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_context(self, + request: Union[gcd_context.CreateContextRequest, dict] = None, + *, + parent: str = None, + context: gcd_context.Context = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_context.Context: + r"""Creates a context. + If the specified context already exists, overrides the + context. + + Args: + request (Union[google.cloud.dialogflow_v2.types.CreateContextRequest, dict]): + The request object. The request message for + [Contexts.CreateContext][google.cloud.dialogflow.v2.Contexts.CreateContext]. + parent (str): + Required. The session to create a context for. Format: + ``projects//agent/sessions/`` or + ``projects//agent/environments//users//sessions/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. If ``User ID`` is not + specified, we assume default '-' user. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + context (google.cloud.dialogflow_v2.types.Context): + Required. The context to create. + This corresponds to the ``context`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Context: + Dialogflow contexts are similar to natural language context. If a person says + to you "they are orange", you need context in order + to understand what "they" is referring to. Similarly, + for Dialogflow to handle an end-user expression like + that, it needs to be provided with context in order + to correctly match an intent. + + Using contexts, you can control the flow of a + conversation. You can configure contexts for an + intent by setting input and output contexts, which + are identified by string names. When an intent is + matched, any configured output contexts for that + intent become active. While any contexts are active, + Dialogflow is more likely to match intents that are + configured with input contexts that correspond to the + currently active contexts. + + For more information about context, see the [Contexts + guide](\ https://cloud.google.com/dialogflow/docs/contexts-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, context]) + if request is 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 gcd_context.CreateContextRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_context.CreateContextRequest): + request = gcd_context.CreateContextRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if context is not None: + request.context = context + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_context] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_context(self, + request: Union[gcd_context.UpdateContextRequest, dict] = None, + *, + context: gcd_context.Context = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_context.Context: + r"""Updates the specified context. + + Args: + request (Union[google.cloud.dialogflow_v2.types.UpdateContextRequest, dict]): + The request object. The request message for + [Contexts.UpdateContext][google.cloud.dialogflow.v2.Contexts.UpdateContext]. + context (google.cloud.dialogflow_v2.types.Context): + Required. The context to update. + This corresponds to the ``context`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Context: + Dialogflow contexts are similar to natural language context. If a person says + to you "they are orange", you need context in order + to understand what "they" is referring to. Similarly, + for Dialogflow to handle an end-user expression like + that, it needs to be provided with context in order + to correctly match an intent. + + Using contexts, you can control the flow of a + conversation. You can configure contexts for an + intent by setting input and output contexts, which + are identified by string names. When an intent is + matched, any configured output contexts for that + intent become active. While any contexts are active, + Dialogflow is more likely to match intents that are + configured with input contexts that correspond to the + currently active contexts. + + For more information about context, see the [Contexts + guide](\ https://cloud.google.com/dialogflow/docs/contexts-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([context, 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 gcd_context.UpdateContextRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_context.UpdateContextRequest): + request = gcd_context.UpdateContextRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if context is not None: + request.context = context + 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_context] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("context.name", request.context.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_context(self, + request: Union[context.DeleteContextRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified context. + + Args: + request (Union[google.cloud.dialogflow_v2.types.DeleteContextRequest, dict]): + The request object. The request message for + [Contexts.DeleteContext][google.cloud.dialogflow.v2.Contexts.DeleteContext]. + name (str): + Required. The name of the context to delete. Format: + ``projects//agent/sessions//contexts/`` + or + ``projects//agent/environments//users//sessions//contexts/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. If ``User ID`` is not + specified, we assume default '-' user. + + 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 context.DeleteContextRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, context.DeleteContextRequest): + request = context.DeleteContextRequest(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_context] + + # Certain 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 delete_all_contexts(self, + request: Union[context.DeleteAllContextsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes all active contexts in the specified session. + + Args: + request (Union[google.cloud.dialogflow_v2.types.DeleteAllContextsRequest, dict]): + The request object. The request message for + [Contexts.DeleteAllContexts][google.cloud.dialogflow.v2.Contexts.DeleteAllContexts]. + parent (str): + Required. The name of the session to delete all contexts + from. Format: + ``projects//agent/sessions/`` or + ``projects//agent/environments//users//sessions/``. + If ``Environment ID`` is not specified we assume default + 'draft' environment. If ``User ID`` is not specified, we + assume default '-' user. + + 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. + """ + # 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 context.DeleteAllContextsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, context.DeleteAllContextsRequest): + request = context.DeleteAllContextsRequest(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.delete_all_contexts] + + # Certain 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. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ContextsClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/pagers.py new file mode 100644 index 000000000..8040073ef --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflow_v2.types import context + + +class ListContextsPager: + """A pager for iterating through ``list_contexts`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListContextsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``contexts`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListContexts`` requests and continue to iterate + through the ``contexts`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListContextsResponse` + 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[..., context.ListContextsResponse], + request: context.ListContextsRequest, + response: context.ListContextsResponse, + *, + 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.dialogflow_v2.types.ListContextsRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListContextsResponse): + 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 = context.ListContextsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[context.ListContextsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[context.Context]: + for page in self.pages: + yield from page.contexts + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListContextsAsyncPager: + """A pager for iterating through ``list_contexts`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListContextsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``contexts`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListContexts`` requests and continue to iterate + through the ``contexts`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListContextsResponse` + 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[context.ListContextsResponse]], + request: context.ListContextsRequest, + response: context.ListContextsResponse, + *, + 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.dialogflow_v2.types.ListContextsRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListContextsResponse): + 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 = context.ListContextsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[context.ListContextsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[context.Context]: + async def async_generator(): + async for page in self.pages: + for response in page.contexts: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/__init__.py new file mode 100644 index 000000000..eb854f545 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/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 ContextsTransport +from .grpc import ContextsGrpcTransport +from .grpc_asyncio import ContextsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ContextsTransport]] +_transport_registry['grpc'] = ContextsGrpcTransport +_transport_registry['grpc_asyncio'] = ContextsGrpcAsyncIOTransport + +__all__ = ( + 'ContextsTransport', + 'ContextsGrpcTransport', + 'ContextsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/base.py new file mode 100644 index 000000000..4eb1a1693 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/base.py @@ -0,0 +1,219 @@ +# -*- 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.types import context +from google.cloud.dialogflow_v2.types import context as gcd_context +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-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ContextsTransport(abc.ABC): + """Abstract transport class for Contexts.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_contexts: gapic_v1.method.wrap_method( + self.list_contexts, + default_timeout=None, + client_info=client_info, + ), + self.get_context: gapic_v1.method.wrap_method( + self.get_context, + default_timeout=None, + client_info=client_info, + ), + self.create_context: gapic_v1.method.wrap_method( + self.create_context, + default_timeout=None, + client_info=client_info, + ), + self.update_context: gapic_v1.method.wrap_method( + self.update_context, + default_timeout=None, + client_info=client_info, + ), + self.delete_context: gapic_v1.method.wrap_method( + self.delete_context, + default_timeout=None, + client_info=client_info, + ), + self.delete_all_contexts: gapic_v1.method.wrap_method( + self.delete_all_contexts, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_contexts(self) -> Callable[ + [context.ListContextsRequest], + Union[ + context.ListContextsResponse, + Awaitable[context.ListContextsResponse] + ]]: + raise NotImplementedError() + + @property + def get_context(self) -> Callable[ + [context.GetContextRequest], + Union[ + context.Context, + Awaitable[context.Context] + ]]: + raise NotImplementedError() + + @property + def create_context(self) -> Callable[ + [gcd_context.CreateContextRequest], + Union[ + gcd_context.Context, + Awaitable[gcd_context.Context] + ]]: + raise NotImplementedError() + + @property + def update_context(self) -> Callable[ + [gcd_context.UpdateContextRequest], + Union[ + gcd_context.Context, + Awaitable[gcd_context.Context] + ]]: + raise NotImplementedError() + + @property + def delete_context(self) -> Callable[ + [context.DeleteContextRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def delete_all_contexts(self) -> Callable[ + [context.DeleteAllContextsRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'ContextsTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/grpc.py new file mode 100644 index 000000000..0f11864da --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/grpc.py @@ -0,0 +1,389 @@ +# -*- 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 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import context +from google.cloud.dialogflow_v2.types import context as gcd_context +from google.protobuf import empty_pb2 # type: ignore +from .base import ContextsTransport, DEFAULT_CLIENT_INFO + + +class ContextsGrpcTransport(ContextsTransport): + """gRPC backend transport for Contexts. + + Service for managing [Contexts][google.cloud.dialogflow.v2.Context]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 = 'dialogflow.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 list_contexts(self) -> Callable[ + [context.ListContextsRequest], + context.ListContextsResponse]: + r"""Return a callable for the list contexts method over gRPC. + + Returns the list of all contexts in the specified + session. + + Returns: + Callable[[~.ListContextsRequest], + ~.ListContextsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_contexts' not in self._stubs: + self._stubs['list_contexts'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Contexts/ListContexts', + request_serializer=context.ListContextsRequest.serialize, + response_deserializer=context.ListContextsResponse.deserialize, + ) + return self._stubs['list_contexts'] + + @property + def get_context(self) -> Callable[ + [context.GetContextRequest], + context.Context]: + r"""Return a callable for the get context method over gRPC. + + Retrieves the specified context. + + Returns: + Callable[[~.GetContextRequest], + ~.Context]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_context' not in self._stubs: + self._stubs['get_context'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Contexts/GetContext', + request_serializer=context.GetContextRequest.serialize, + response_deserializer=context.Context.deserialize, + ) + return self._stubs['get_context'] + + @property + def create_context(self) -> Callable[ + [gcd_context.CreateContextRequest], + gcd_context.Context]: + r"""Return a callable for the create context method over gRPC. + + Creates a context. + If the specified context already exists, overrides the + context. + + Returns: + Callable[[~.CreateContextRequest], + ~.Context]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_context' not in self._stubs: + self._stubs['create_context'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Contexts/CreateContext', + request_serializer=gcd_context.CreateContextRequest.serialize, + response_deserializer=gcd_context.Context.deserialize, + ) + return self._stubs['create_context'] + + @property + def update_context(self) -> Callable[ + [gcd_context.UpdateContextRequest], + gcd_context.Context]: + r"""Return a callable for the update context method over gRPC. + + Updates the specified context. + + Returns: + Callable[[~.UpdateContextRequest], + ~.Context]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_context' not in self._stubs: + self._stubs['update_context'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Contexts/UpdateContext', + request_serializer=gcd_context.UpdateContextRequest.serialize, + response_deserializer=gcd_context.Context.deserialize, + ) + return self._stubs['update_context'] + + @property + def delete_context(self) -> Callable[ + [context.DeleteContextRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete context method over gRPC. + + Deletes the specified context. + + Returns: + Callable[[~.DeleteContextRequest], + ~.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_context' not in self._stubs: + self._stubs['delete_context'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Contexts/DeleteContext', + request_serializer=context.DeleteContextRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_context'] + + @property + def delete_all_contexts(self) -> Callable[ + [context.DeleteAllContextsRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete all contexts method over gRPC. + + Deletes all active contexts in the specified session. + + Returns: + Callable[[~.DeleteAllContextsRequest], + ~.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_all_contexts' not in self._stubs: + self._stubs['delete_all_contexts'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Contexts/DeleteAllContexts', + request_serializer=context.DeleteAllContextsRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_all_contexts'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'ContextsGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/grpc_asyncio.py new file mode 100644 index 000000000..80e770283 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/grpc_asyncio.py @@ -0,0 +1,393 @@ +# -*- 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 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import context +from google.cloud.dialogflow_v2.types import context as gcd_context +from google.protobuf import empty_pb2 # type: ignore +from .base import ContextsTransport, DEFAULT_CLIENT_INFO +from .grpc import ContextsGrpcTransport + + +class ContextsGrpcAsyncIOTransport(ContextsTransport): + """gRPC AsyncIO backend transport for Contexts. + + Service for managing [Contexts][google.cloud.dialogflow.v2.Context]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 list_contexts(self) -> Callable[ + [context.ListContextsRequest], + Awaitable[context.ListContextsResponse]]: + r"""Return a callable for the list contexts method over gRPC. + + Returns the list of all contexts in the specified + session. + + Returns: + Callable[[~.ListContextsRequest], + Awaitable[~.ListContextsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_contexts' not in self._stubs: + self._stubs['list_contexts'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Contexts/ListContexts', + request_serializer=context.ListContextsRequest.serialize, + response_deserializer=context.ListContextsResponse.deserialize, + ) + return self._stubs['list_contexts'] + + @property + def get_context(self) -> Callable[ + [context.GetContextRequest], + Awaitable[context.Context]]: + r"""Return a callable for the get context method over gRPC. + + Retrieves the specified context. + + Returns: + Callable[[~.GetContextRequest], + Awaitable[~.Context]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_context' not in self._stubs: + self._stubs['get_context'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Contexts/GetContext', + request_serializer=context.GetContextRequest.serialize, + response_deserializer=context.Context.deserialize, + ) + return self._stubs['get_context'] + + @property + def create_context(self) -> Callable[ + [gcd_context.CreateContextRequest], + Awaitable[gcd_context.Context]]: + r"""Return a callable for the create context method over gRPC. + + Creates a context. + If the specified context already exists, overrides the + context. + + Returns: + Callable[[~.CreateContextRequest], + Awaitable[~.Context]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_context' not in self._stubs: + self._stubs['create_context'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Contexts/CreateContext', + request_serializer=gcd_context.CreateContextRequest.serialize, + response_deserializer=gcd_context.Context.deserialize, + ) + return self._stubs['create_context'] + + @property + def update_context(self) -> Callable[ + [gcd_context.UpdateContextRequest], + Awaitable[gcd_context.Context]]: + r"""Return a callable for the update context method over gRPC. + + Updates the specified context. + + Returns: + Callable[[~.UpdateContextRequest], + Awaitable[~.Context]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_context' not in self._stubs: + self._stubs['update_context'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Contexts/UpdateContext', + request_serializer=gcd_context.UpdateContextRequest.serialize, + response_deserializer=gcd_context.Context.deserialize, + ) + return self._stubs['update_context'] + + @property + def delete_context(self) -> Callable[ + [context.DeleteContextRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete context method over gRPC. + + Deletes the specified context. + + Returns: + Callable[[~.DeleteContextRequest], + 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_context' not in self._stubs: + self._stubs['delete_context'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Contexts/DeleteContext', + request_serializer=context.DeleteContextRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_context'] + + @property + def delete_all_contexts(self) -> Callable[ + [context.DeleteAllContextsRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete all contexts method over gRPC. + + Deletes all active contexts in the specified session. + + Returns: + Callable[[~.DeleteAllContextsRequest], + 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_all_contexts' not in self._stubs: + self._stubs['delete_all_contexts'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Contexts/DeleteAllContexts', + request_serializer=context.DeleteAllContextsRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_all_contexts'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ContextsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/__init__.py new file mode 100644 index 000000000..3e8e4ea19 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/__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 ConversationProfilesClient +from .async_client import ConversationProfilesAsyncClient + +__all__ = ( + 'ConversationProfilesClient', + 'ConversationProfilesAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/async_client.py new file mode 100644 index 000000000..004fd8a29 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/async_client.py @@ -0,0 +1,603 @@ +# -*- 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 + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2.services.conversation_profiles import pagers +from google.cloud.dialogflow_v2.types import audio_config +from google.cloud.dialogflow_v2.types import conversation_profile +from google.cloud.dialogflow_v2.types import conversation_profile as gcd_conversation_profile +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ConversationProfilesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ConversationProfilesGrpcAsyncIOTransport +from .client import ConversationProfilesClient + + +class ConversationProfilesAsyncClient: + """Service for managing + [ConversationProfiles][google.cloud.dialogflow.v2.ConversationProfile]. + """ + + _client: ConversationProfilesClient + + DEFAULT_ENDPOINT = ConversationProfilesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ConversationProfilesClient.DEFAULT_MTLS_ENDPOINT + + agent_path = staticmethod(ConversationProfilesClient.agent_path) + parse_agent_path = staticmethod(ConversationProfilesClient.parse_agent_path) + conversation_model_path = staticmethod(ConversationProfilesClient.conversation_model_path) + parse_conversation_model_path = staticmethod(ConversationProfilesClient.parse_conversation_model_path) + conversation_profile_path = staticmethod(ConversationProfilesClient.conversation_profile_path) + parse_conversation_profile_path = staticmethod(ConversationProfilesClient.parse_conversation_profile_path) + cx_security_settings_path = staticmethod(ConversationProfilesClient.cx_security_settings_path) + parse_cx_security_settings_path = staticmethod(ConversationProfilesClient.parse_cx_security_settings_path) + document_path = staticmethod(ConversationProfilesClient.document_path) + parse_document_path = staticmethod(ConversationProfilesClient.parse_document_path) + knowledge_base_path = staticmethod(ConversationProfilesClient.knowledge_base_path) + parse_knowledge_base_path = staticmethod(ConversationProfilesClient.parse_knowledge_base_path) + common_billing_account_path = staticmethod(ConversationProfilesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ConversationProfilesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ConversationProfilesClient.common_folder_path) + parse_common_folder_path = staticmethod(ConversationProfilesClient.parse_common_folder_path) + common_organization_path = staticmethod(ConversationProfilesClient.common_organization_path) + parse_common_organization_path = staticmethod(ConversationProfilesClient.parse_common_organization_path) + common_project_path = staticmethod(ConversationProfilesClient.common_project_path) + parse_common_project_path = staticmethod(ConversationProfilesClient.parse_common_project_path) + common_location_path = staticmethod(ConversationProfilesClient.common_location_path) + parse_common_location_path = staticmethod(ConversationProfilesClient.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: + ConversationProfilesAsyncClient: The constructed client. + """ + return ConversationProfilesClient.from_service_account_info.__func__(ConversationProfilesAsyncClient, 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: + ConversationProfilesAsyncClient: The constructed client. + """ + return ConversationProfilesClient.from_service_account_file.__func__(ConversationProfilesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ConversationProfilesTransport: + """Returns the transport used by the client instance. + + Returns: + ConversationProfilesTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ConversationProfilesClient).get_transport_class, type(ConversationProfilesClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ConversationProfilesTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the conversation profiles 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, ~.ConversationProfilesTransport]): 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 = ConversationProfilesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_conversation_profiles(self, + request: Union[conversation_profile.ListConversationProfilesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListConversationProfilesAsyncPager: + r"""Returns the list of all conversation profiles in the + specified project. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListConversationProfilesRequest, dict]): + The request object. The request message for + [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2.ConversationProfiles.ListConversationProfiles]. + parent (:class:`str`): + Required. The project to list all conversation profiles + from. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.services.conversation_profiles.pagers.ListConversationProfilesAsyncPager: + The response message for + [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2.ConversationProfiles.ListConversationProfiles]. + + 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 = conversation_profile.ListConversationProfilesRequest(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_conversation_profiles, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListConversationProfilesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_conversation_profile(self, + request: Union[conversation_profile.GetConversationProfileRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation_profile.ConversationProfile: + r"""Retrieves the specified conversation profile. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetConversationProfileRequest, dict]): + The request object. The request message for + [ConversationProfiles.GetConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.GetConversationProfile]. + name (:class:`str`): + Required. The resource name of the conversation profile. + Format: + ``projects//locations//conversationProfiles/``. + + 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.dialogflow_v2.types.ConversationProfile: + Defines the services to connect to + incoming Dialogflow conversations. + + """ + # 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 = conversation_profile.GetConversationProfileRequest(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_conversation_profile, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_conversation_profile(self, + request: Union[gcd_conversation_profile.CreateConversationProfileRequest, dict] = None, + *, + parent: str = None, + conversation_profile: gcd_conversation_profile.ConversationProfile = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_conversation_profile.ConversationProfile: + r"""Creates a conversation profile in the specified project. + + [ConversationProfile.CreateTime][] and + [ConversationProfile.UpdateTime][] aren't populated in the + response. You can retrieve them via + [GetConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.GetConversationProfile] + API. + + Args: + request (Union[google.cloud.dialogflow_v2.types.CreateConversationProfileRequest, dict]): + The request object. The request message for + [ConversationProfiles.CreateConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.CreateConversationProfile]. + parent (:class:`str`): + Required. The project to create a conversation profile + for. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + conversation_profile (:class:`google.cloud.dialogflow_v2.types.ConversationProfile`): + Required. The conversation profile to + create. + + This corresponds to the ``conversation_profile`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.ConversationProfile: + Defines the services to connect to + incoming Dialogflow conversations. + + """ + # 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, conversation_profile]) + if request is 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 = gcd_conversation_profile.CreateConversationProfileRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if conversation_profile is not None: + request.conversation_profile = conversation_profile + + # 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_conversation_profile, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_conversation_profile(self, + request: Union[gcd_conversation_profile.UpdateConversationProfileRequest, dict] = None, + *, + conversation_profile: gcd_conversation_profile.ConversationProfile = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_conversation_profile.ConversationProfile: + r"""Updates the specified conversation profile. + + [ConversationProfile.CreateTime][] and + [ConversationProfile.UpdateTime][] aren't populated in the + response. You can retrieve them via + [GetConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.GetConversationProfile] + API. + + Args: + request (Union[google.cloud.dialogflow_v2.types.UpdateConversationProfileRequest, dict]): + The request object. The request message for + [ConversationProfiles.UpdateConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.UpdateConversationProfile]. + conversation_profile (:class:`google.cloud.dialogflow_v2.types.ConversationProfile`): + Required. The conversation profile to + update. + + This corresponds to the ``conversation_profile`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The mask to control which + fields to update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.ConversationProfile: + Defines the services to connect to + incoming Dialogflow conversations. + + """ + # 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([conversation_profile, 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 = gcd_conversation_profile.UpdateConversationProfileRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if conversation_profile is not None: + request.conversation_profile = conversation_profile + 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_conversation_profile, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("conversation_profile.name", request.conversation_profile.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_conversation_profile(self, + request: Union[conversation_profile.DeleteConversationProfileRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified conversation profile. + + Args: + request (Union[google.cloud.dialogflow_v2.types.DeleteConversationProfileRequest, dict]): + The request object. The request message for + [ConversationProfiles.DeleteConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.DeleteConversationProfile]. + This operation fails if the conversation profile is + still referenced from a phone number. + name (:class:`str`): + Required. The name of the conversation profile to + delete. Format: + ``projects//locations//conversationProfiles/``. + + 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 = conversation_profile.DeleteConversationProfileRequest(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_conversation_profile, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ConversationProfilesAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/client.py new file mode 100644 index 000000000..2f5aa4db9 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/client.py @@ -0,0 +1,846 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2.services.conversation_profiles import pagers +from google.cloud.dialogflow_v2.types import audio_config +from google.cloud.dialogflow_v2.types import conversation_profile +from google.cloud.dialogflow_v2.types import conversation_profile as gcd_conversation_profile +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ConversationProfilesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ConversationProfilesGrpcTransport +from .transports.grpc_asyncio import ConversationProfilesGrpcAsyncIOTransport + + +class ConversationProfilesClientMeta(type): + """Metaclass for the ConversationProfiles 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[ConversationProfilesTransport]] + _transport_registry["grpc"] = ConversationProfilesGrpcTransport + _transport_registry["grpc_asyncio"] = ConversationProfilesGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ConversationProfilesTransport]: + """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 ConversationProfilesClient(metaclass=ConversationProfilesClientMeta): + """Service for managing + [ConversationProfiles][google.cloud.dialogflow.v2.ConversationProfile]. + """ + + @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 = "dialogflow.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: + ConversationProfilesClient: 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: + ConversationProfilesClient: 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) -> ConversationProfilesTransport: + """Returns the transport used by the client instance. + + Returns: + ConversationProfilesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def agent_path(project: str,) -> str: + """Returns a fully-qualified agent string.""" + return "projects/{project}/agent".format(project=project, ) + + @staticmethod + def parse_agent_path(path: str) -> Dict[str,str]: + """Parses a agent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent$", path) + return m.groupdict() if m else {} + + @staticmethod + def conversation_model_path(project: str,location: str,conversation_model: str,) -> str: + """Returns a fully-qualified conversation_model string.""" + return "projects/{project}/locations/{location}/conversationModels/{conversation_model}".format(project=project, location=location, conversation_model=conversation_model, ) + + @staticmethod + def parse_conversation_model_path(path: str) -> Dict[str,str]: + """Parses a conversation_model path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/conversationModels/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def conversation_profile_path(project: str,conversation_profile: str,) -> str: + """Returns a fully-qualified conversation_profile string.""" + return "projects/{project}/conversationProfiles/{conversation_profile}".format(project=project, conversation_profile=conversation_profile, ) + + @staticmethod + def parse_conversation_profile_path(path: str) -> Dict[str,str]: + """Parses a conversation_profile path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/conversationProfiles/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def cx_security_settings_path(project: str,location: str,security_settings: str,) -> str: + """Returns a fully-qualified cx_security_settings string.""" + return "projects/{project}/locations/{location}/securitySettings/{security_settings}".format(project=project, location=location, security_settings=security_settings, ) + + @staticmethod + def parse_cx_security_settings_path(path: str) -> Dict[str,str]: + """Parses a cx_security_settings path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/securitySettings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def document_path(project: str,knowledge_base: str,document: str,) -> str: + """Returns a fully-qualified document string.""" + return "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format(project=project, knowledge_base=knowledge_base, document=document, ) + + @staticmethod + def parse_document_path(path: str) -> Dict[str,str]: + """Parses a document path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/knowledgeBases/(?P.+?)/documents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def knowledge_base_path(project: str,knowledge_base: str,) -> str: + """Returns a fully-qualified knowledge_base string.""" + return "projects/{project}/knowledgeBases/{knowledge_base}".format(project=project, knowledge_base=knowledge_base, ) + + @staticmethod + def parse_knowledge_base_path(path: str) -> Dict[str,str]: + """Parses a knowledge_base path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/knowledgeBases/(?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, ConversationProfilesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the conversation profiles 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, ConversationProfilesTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, ConversationProfilesTransport): + # transport is a ConversationProfilesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_conversation_profiles(self, + request: Union[conversation_profile.ListConversationProfilesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListConversationProfilesPager: + r"""Returns the list of all conversation profiles in the + specified project. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListConversationProfilesRequest, dict]): + The request object. The request message for + [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2.ConversationProfiles.ListConversationProfiles]. + parent (str): + Required. The project to list all conversation profiles + from. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.services.conversation_profiles.pagers.ListConversationProfilesPager: + The response message for + [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2.ConversationProfiles.ListConversationProfiles]. + + 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 conversation_profile.ListConversationProfilesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversation_profile.ListConversationProfilesRequest): + request = conversation_profile.ListConversationProfilesRequest(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_conversation_profiles] + + # Certain 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.ListConversationProfilesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_conversation_profile(self, + request: Union[conversation_profile.GetConversationProfileRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation_profile.ConversationProfile: + r"""Retrieves the specified conversation profile. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetConversationProfileRequest, dict]): + The request object. The request message for + [ConversationProfiles.GetConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.GetConversationProfile]. + name (str): + Required. The resource name of the conversation profile. + Format: + ``projects//locations//conversationProfiles/``. + + 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.dialogflow_v2.types.ConversationProfile: + Defines the services to connect to + incoming Dialogflow conversations. + + """ + # 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 conversation_profile.GetConversationProfileRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversation_profile.GetConversationProfileRequest): + request = conversation_profile.GetConversationProfileRequest(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_conversation_profile] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_conversation_profile(self, + request: Union[gcd_conversation_profile.CreateConversationProfileRequest, dict] = None, + *, + parent: str = None, + conversation_profile: gcd_conversation_profile.ConversationProfile = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_conversation_profile.ConversationProfile: + r"""Creates a conversation profile in the specified project. + + [ConversationProfile.CreateTime][] and + [ConversationProfile.UpdateTime][] aren't populated in the + response. You can retrieve them via + [GetConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.GetConversationProfile] + API. + + Args: + request (Union[google.cloud.dialogflow_v2.types.CreateConversationProfileRequest, dict]): + The request object. The request message for + [ConversationProfiles.CreateConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.CreateConversationProfile]. + parent (str): + Required. The project to create a conversation profile + for. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + conversation_profile (google.cloud.dialogflow_v2.types.ConversationProfile): + Required. The conversation profile to + create. + + This corresponds to the ``conversation_profile`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.ConversationProfile: + Defines the services to connect to + incoming Dialogflow conversations. + + """ + # 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, conversation_profile]) + if request is 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 gcd_conversation_profile.CreateConversationProfileRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_conversation_profile.CreateConversationProfileRequest): + request = gcd_conversation_profile.CreateConversationProfileRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if conversation_profile is not None: + request.conversation_profile = conversation_profile + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_conversation_profile] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_conversation_profile(self, + request: Union[gcd_conversation_profile.UpdateConversationProfileRequest, dict] = None, + *, + conversation_profile: gcd_conversation_profile.ConversationProfile = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_conversation_profile.ConversationProfile: + r"""Updates the specified conversation profile. + + [ConversationProfile.CreateTime][] and + [ConversationProfile.UpdateTime][] aren't populated in the + response. You can retrieve them via + [GetConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.GetConversationProfile] + API. + + Args: + request (Union[google.cloud.dialogflow_v2.types.UpdateConversationProfileRequest, dict]): + The request object. The request message for + [ConversationProfiles.UpdateConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.UpdateConversationProfile]. + conversation_profile (google.cloud.dialogflow_v2.types.ConversationProfile): + Required. The conversation profile to + update. + + This corresponds to the ``conversation_profile`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which + fields to update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.ConversationProfile: + Defines the services to connect to + incoming Dialogflow conversations. + + """ + # 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([conversation_profile, 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 gcd_conversation_profile.UpdateConversationProfileRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_conversation_profile.UpdateConversationProfileRequest): + request = gcd_conversation_profile.UpdateConversationProfileRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if conversation_profile is not None: + request.conversation_profile = conversation_profile + 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_conversation_profile] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("conversation_profile.name", request.conversation_profile.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_conversation_profile(self, + request: Union[conversation_profile.DeleteConversationProfileRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified conversation profile. + + Args: + request (Union[google.cloud.dialogflow_v2.types.DeleteConversationProfileRequest, dict]): + The request object. The request message for + [ConversationProfiles.DeleteConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.DeleteConversationProfile]. + This operation fails if the conversation profile is + still referenced from a phone number. + name (str): + Required. The name of the conversation profile to + delete. Format: + ``projects//locations//conversationProfiles/``. + + 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 conversation_profile.DeleteConversationProfileRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversation_profile.DeleteConversationProfileRequest): + request = conversation_profile.DeleteConversationProfileRequest(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_conversation_profile] + + # Certain 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 __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ConversationProfilesClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/pagers.py new file mode 100644 index 000000000..9ea39a14a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflow_v2.types import conversation_profile + + +class ListConversationProfilesPager: + """A pager for iterating through ``list_conversation_profiles`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListConversationProfilesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``conversation_profiles`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListConversationProfiles`` requests and continue to iterate + through the ``conversation_profiles`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListConversationProfilesResponse` + 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[..., conversation_profile.ListConversationProfilesResponse], + request: conversation_profile.ListConversationProfilesRequest, + response: conversation_profile.ListConversationProfilesResponse, + *, + 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.dialogflow_v2.types.ListConversationProfilesRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListConversationProfilesResponse): + 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 = conversation_profile.ListConversationProfilesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[conversation_profile.ListConversationProfilesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[conversation_profile.ConversationProfile]: + for page in self.pages: + yield from page.conversation_profiles + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListConversationProfilesAsyncPager: + """A pager for iterating through ``list_conversation_profiles`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListConversationProfilesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``conversation_profiles`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListConversationProfiles`` requests and continue to iterate + through the ``conversation_profiles`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListConversationProfilesResponse` + 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[conversation_profile.ListConversationProfilesResponse]], + request: conversation_profile.ListConversationProfilesRequest, + response: conversation_profile.ListConversationProfilesResponse, + *, + 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.dialogflow_v2.types.ListConversationProfilesRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListConversationProfilesResponse): + 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 = conversation_profile.ListConversationProfilesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[conversation_profile.ListConversationProfilesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[conversation_profile.ConversationProfile]: + async def async_generator(): + async for page in self.pages: + for response in page.conversation_profiles: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/__init__.py new file mode 100644 index 000000000..19a679f49 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/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 ConversationProfilesTransport +from .grpc import ConversationProfilesGrpcTransport +from .grpc_asyncio import ConversationProfilesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ConversationProfilesTransport]] +_transport_registry['grpc'] = ConversationProfilesGrpcTransport +_transport_registry['grpc_asyncio'] = ConversationProfilesGrpcAsyncIOTransport + +__all__ = ( + 'ConversationProfilesTransport', + 'ConversationProfilesGrpcTransport', + 'ConversationProfilesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/base.py new file mode 100644 index 000000000..3f12df793 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/base.py @@ -0,0 +1,205 @@ +# -*- 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.types import conversation_profile +from google.cloud.dialogflow_v2.types import conversation_profile as gcd_conversation_profile +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-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ConversationProfilesTransport(abc.ABC): + """Abstract transport class for ConversationProfiles.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_conversation_profiles: gapic_v1.method.wrap_method( + self.list_conversation_profiles, + default_timeout=None, + client_info=client_info, + ), + self.get_conversation_profile: gapic_v1.method.wrap_method( + self.get_conversation_profile, + default_timeout=None, + client_info=client_info, + ), + self.create_conversation_profile: gapic_v1.method.wrap_method( + self.create_conversation_profile, + default_timeout=None, + client_info=client_info, + ), + self.update_conversation_profile: gapic_v1.method.wrap_method( + self.update_conversation_profile, + default_timeout=None, + client_info=client_info, + ), + self.delete_conversation_profile: gapic_v1.method.wrap_method( + self.delete_conversation_profile, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_conversation_profiles(self) -> Callable[ + [conversation_profile.ListConversationProfilesRequest], + Union[ + conversation_profile.ListConversationProfilesResponse, + Awaitable[conversation_profile.ListConversationProfilesResponse] + ]]: + raise NotImplementedError() + + @property + def get_conversation_profile(self) -> Callable[ + [conversation_profile.GetConversationProfileRequest], + Union[ + conversation_profile.ConversationProfile, + Awaitable[conversation_profile.ConversationProfile] + ]]: + raise NotImplementedError() + + @property + def create_conversation_profile(self) -> Callable[ + [gcd_conversation_profile.CreateConversationProfileRequest], + Union[ + gcd_conversation_profile.ConversationProfile, + Awaitable[gcd_conversation_profile.ConversationProfile] + ]]: + raise NotImplementedError() + + @property + def update_conversation_profile(self) -> Callable[ + [gcd_conversation_profile.UpdateConversationProfileRequest], + Union[ + gcd_conversation_profile.ConversationProfile, + Awaitable[gcd_conversation_profile.ConversationProfile] + ]]: + raise NotImplementedError() + + @property + def delete_conversation_profile(self) -> Callable[ + [conversation_profile.DeleteConversationProfileRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'ConversationProfilesTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc.py new file mode 100644 index 000000000..f34527600 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc.py @@ -0,0 +1,374 @@ +# -*- 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 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import conversation_profile +from google.cloud.dialogflow_v2.types import conversation_profile as gcd_conversation_profile +from google.protobuf import empty_pb2 # type: ignore +from .base import ConversationProfilesTransport, DEFAULT_CLIENT_INFO + + +class ConversationProfilesGrpcTransport(ConversationProfilesTransport): + """gRPC backend transport for ConversationProfiles. + + Service for managing + [ConversationProfiles][google.cloud.dialogflow.v2.ConversationProfile]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 = 'dialogflow.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 list_conversation_profiles(self) -> Callable[ + [conversation_profile.ListConversationProfilesRequest], + conversation_profile.ListConversationProfilesResponse]: + r"""Return a callable for the list conversation profiles method over gRPC. + + Returns the list of all conversation profiles in the + specified project. + + Returns: + Callable[[~.ListConversationProfilesRequest], + ~.ListConversationProfilesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation_profiles' not in self._stubs: + self._stubs['list_conversation_profiles'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.ConversationProfiles/ListConversationProfiles', + request_serializer=conversation_profile.ListConversationProfilesRequest.serialize, + response_deserializer=conversation_profile.ListConversationProfilesResponse.deserialize, + ) + return self._stubs['list_conversation_profiles'] + + @property + def get_conversation_profile(self) -> Callable[ + [conversation_profile.GetConversationProfileRequest], + conversation_profile.ConversationProfile]: + r"""Return a callable for the get conversation profile method over gRPC. + + Retrieves the specified conversation profile. + + Returns: + Callable[[~.GetConversationProfileRequest], + ~.ConversationProfile]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation_profile' not in self._stubs: + self._stubs['get_conversation_profile'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.ConversationProfiles/GetConversationProfile', + request_serializer=conversation_profile.GetConversationProfileRequest.serialize, + response_deserializer=conversation_profile.ConversationProfile.deserialize, + ) + return self._stubs['get_conversation_profile'] + + @property + def create_conversation_profile(self) -> Callable[ + [gcd_conversation_profile.CreateConversationProfileRequest], + gcd_conversation_profile.ConversationProfile]: + r"""Return a callable for the create conversation profile method over gRPC. + + Creates a conversation profile in the specified project. + + [ConversationProfile.CreateTime][] and + [ConversationProfile.UpdateTime][] aren't populated in the + response. You can retrieve them via + [GetConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.GetConversationProfile] + API. + + Returns: + Callable[[~.CreateConversationProfileRequest], + ~.ConversationProfile]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation_profile' not in self._stubs: + self._stubs['create_conversation_profile'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.ConversationProfiles/CreateConversationProfile', + request_serializer=gcd_conversation_profile.CreateConversationProfileRequest.serialize, + response_deserializer=gcd_conversation_profile.ConversationProfile.deserialize, + ) + return self._stubs['create_conversation_profile'] + + @property + def update_conversation_profile(self) -> Callable[ + [gcd_conversation_profile.UpdateConversationProfileRequest], + gcd_conversation_profile.ConversationProfile]: + r"""Return a callable for the update conversation profile method over gRPC. + + Updates the specified conversation profile. + + [ConversationProfile.CreateTime][] and + [ConversationProfile.UpdateTime][] aren't populated in the + response. You can retrieve them via + [GetConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.GetConversationProfile] + API. + + Returns: + Callable[[~.UpdateConversationProfileRequest], + ~.ConversationProfile]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation_profile' not in self._stubs: + self._stubs['update_conversation_profile'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.ConversationProfiles/UpdateConversationProfile', + request_serializer=gcd_conversation_profile.UpdateConversationProfileRequest.serialize, + response_deserializer=gcd_conversation_profile.ConversationProfile.deserialize, + ) + return self._stubs['update_conversation_profile'] + + @property + def delete_conversation_profile(self) -> Callable[ + [conversation_profile.DeleteConversationProfileRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete conversation profile method over gRPC. + + Deletes the specified conversation profile. + + Returns: + Callable[[~.DeleteConversationProfileRequest], + ~.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_conversation_profile' not in self._stubs: + self._stubs['delete_conversation_profile'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.ConversationProfiles/DeleteConversationProfile', + request_serializer=conversation_profile.DeleteConversationProfileRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_conversation_profile'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'ConversationProfilesGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc_asyncio.py new file mode 100644 index 000000000..cff2d236b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc_asyncio.py @@ -0,0 +1,378 @@ +# -*- 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 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import conversation_profile +from google.cloud.dialogflow_v2.types import conversation_profile as gcd_conversation_profile +from google.protobuf import empty_pb2 # type: ignore +from .base import ConversationProfilesTransport, DEFAULT_CLIENT_INFO +from .grpc import ConversationProfilesGrpcTransport + + +class ConversationProfilesGrpcAsyncIOTransport(ConversationProfilesTransport): + """gRPC AsyncIO backend transport for ConversationProfiles. + + Service for managing + [ConversationProfiles][google.cloud.dialogflow.v2.ConversationProfile]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 list_conversation_profiles(self) -> Callable[ + [conversation_profile.ListConversationProfilesRequest], + Awaitable[conversation_profile.ListConversationProfilesResponse]]: + r"""Return a callable for the list conversation profiles method over gRPC. + + Returns the list of all conversation profiles in the + specified project. + + Returns: + Callable[[~.ListConversationProfilesRequest], + Awaitable[~.ListConversationProfilesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation_profiles' not in self._stubs: + self._stubs['list_conversation_profiles'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.ConversationProfiles/ListConversationProfiles', + request_serializer=conversation_profile.ListConversationProfilesRequest.serialize, + response_deserializer=conversation_profile.ListConversationProfilesResponse.deserialize, + ) + return self._stubs['list_conversation_profiles'] + + @property + def get_conversation_profile(self) -> Callable[ + [conversation_profile.GetConversationProfileRequest], + Awaitable[conversation_profile.ConversationProfile]]: + r"""Return a callable for the get conversation profile method over gRPC. + + Retrieves the specified conversation profile. + + Returns: + Callable[[~.GetConversationProfileRequest], + Awaitable[~.ConversationProfile]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation_profile' not in self._stubs: + self._stubs['get_conversation_profile'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.ConversationProfiles/GetConversationProfile', + request_serializer=conversation_profile.GetConversationProfileRequest.serialize, + response_deserializer=conversation_profile.ConversationProfile.deserialize, + ) + return self._stubs['get_conversation_profile'] + + @property + def create_conversation_profile(self) -> Callable[ + [gcd_conversation_profile.CreateConversationProfileRequest], + Awaitable[gcd_conversation_profile.ConversationProfile]]: + r"""Return a callable for the create conversation profile method over gRPC. + + Creates a conversation profile in the specified project. + + [ConversationProfile.CreateTime][] and + [ConversationProfile.UpdateTime][] aren't populated in the + response. You can retrieve them via + [GetConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.GetConversationProfile] + API. + + Returns: + Callable[[~.CreateConversationProfileRequest], + Awaitable[~.ConversationProfile]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation_profile' not in self._stubs: + self._stubs['create_conversation_profile'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.ConversationProfiles/CreateConversationProfile', + request_serializer=gcd_conversation_profile.CreateConversationProfileRequest.serialize, + response_deserializer=gcd_conversation_profile.ConversationProfile.deserialize, + ) + return self._stubs['create_conversation_profile'] + + @property + def update_conversation_profile(self) -> Callable[ + [gcd_conversation_profile.UpdateConversationProfileRequest], + Awaitable[gcd_conversation_profile.ConversationProfile]]: + r"""Return a callable for the update conversation profile method over gRPC. + + Updates the specified conversation profile. + + [ConversationProfile.CreateTime][] and + [ConversationProfile.UpdateTime][] aren't populated in the + response. You can retrieve them via + [GetConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.GetConversationProfile] + API. + + Returns: + Callable[[~.UpdateConversationProfileRequest], + Awaitable[~.ConversationProfile]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation_profile' not in self._stubs: + self._stubs['update_conversation_profile'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.ConversationProfiles/UpdateConversationProfile', + request_serializer=gcd_conversation_profile.UpdateConversationProfileRequest.serialize, + response_deserializer=gcd_conversation_profile.ConversationProfile.deserialize, + ) + return self._stubs['update_conversation_profile'] + + @property + def delete_conversation_profile(self) -> Callable[ + [conversation_profile.DeleteConversationProfileRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete conversation profile method over gRPC. + + Deletes the specified conversation profile. + + Returns: + Callable[[~.DeleteConversationProfileRequest], + 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_conversation_profile' not in self._stubs: + self._stubs['delete_conversation_profile'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.ConversationProfiles/DeleteConversationProfile', + request_serializer=conversation_profile.DeleteConversationProfileRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_conversation_profile'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ConversationProfilesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/__init__.py new file mode 100644 index 000000000..0445da9c4 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/__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 ConversationsClient +from .async_client import ConversationsAsyncClient + +__all__ = ( + 'ConversationsClient', + 'ConversationsAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/async_client.py new file mode 100644 index 000000000..d1a804a77 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/async_client.py @@ -0,0 +1,632 @@ +# -*- 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 + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2.services.conversations import pagers +from google.cloud.dialogflow_v2.types import conversation +from google.cloud.dialogflow_v2.types import conversation as gcd_conversation +from google.cloud.dialogflow_v2.types import participant +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ConversationsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ConversationsGrpcAsyncIOTransport +from .client import ConversationsClient + + +class ConversationsAsyncClient: + """Service for managing + [Conversations][google.cloud.dialogflow.v2.Conversation]. + """ + + _client: ConversationsClient + + DEFAULT_ENDPOINT = ConversationsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ConversationsClient.DEFAULT_MTLS_ENDPOINT + + conversation_path = staticmethod(ConversationsClient.conversation_path) + parse_conversation_path = staticmethod(ConversationsClient.parse_conversation_path) + conversation_profile_path = staticmethod(ConversationsClient.conversation_profile_path) + parse_conversation_profile_path = staticmethod(ConversationsClient.parse_conversation_profile_path) + message_path = staticmethod(ConversationsClient.message_path) + parse_message_path = staticmethod(ConversationsClient.parse_message_path) + common_billing_account_path = staticmethod(ConversationsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ConversationsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ConversationsClient.common_folder_path) + parse_common_folder_path = staticmethod(ConversationsClient.parse_common_folder_path) + common_organization_path = staticmethod(ConversationsClient.common_organization_path) + parse_common_organization_path = staticmethod(ConversationsClient.parse_common_organization_path) + common_project_path = staticmethod(ConversationsClient.common_project_path) + parse_common_project_path = staticmethod(ConversationsClient.parse_common_project_path) + common_location_path = staticmethod(ConversationsClient.common_location_path) + parse_common_location_path = staticmethod(ConversationsClient.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: + ConversationsAsyncClient: The constructed client. + """ + return ConversationsClient.from_service_account_info.__func__(ConversationsAsyncClient, 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: + ConversationsAsyncClient: The constructed client. + """ + return ConversationsClient.from_service_account_file.__func__(ConversationsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ConversationsTransport: + """Returns the transport used by the client instance. + + Returns: + ConversationsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ConversationsClient).get_transport_class, type(ConversationsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ConversationsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the conversations 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, ~.ConversationsTransport]): 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 = ConversationsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_conversation(self, + request: Union[gcd_conversation.CreateConversationRequest, dict] = None, + *, + parent: str = None, + conversation: gcd_conversation.Conversation = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_conversation.Conversation: + r"""Creates a new conversation. Conversations are auto-completed + after 24 hours. + + Conversation Lifecycle: There are two stages during a + conversation: Automated Agent Stage and Assist Stage. + + For Automated Agent Stage, there will be a dialogflow agent + responding to user queries. + + For Assist Stage, there's no dialogflow agent responding to user + queries. But we will provide suggestions which are generated + from conversation. + + If + [Conversation.conversation_profile][google.cloud.dialogflow.v2.Conversation.conversation_profile] + is configured for a dialogflow agent, conversation will start + from ``Automated Agent Stage``, otherwise, it will start from + ``Assist Stage``. And during ``Automated Agent Stage``, once an + [Intent][google.cloud.dialogflow.v2.Intent] with + [Intent.live_agent_handoff][google.cloud.dialogflow.v2.Intent.live_agent_handoff] + is triggered, conversation will transfer to Assist Stage. + + Args: + request (Union[google.cloud.dialogflow_v2.types.CreateConversationRequest, dict]): + The request object. The request message for + [Conversations.CreateConversation][google.cloud.dialogflow.v2.Conversations.CreateConversation]. + parent (:class:`str`): + Required. Resource identifier of the project creating + the conversation. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + conversation (:class:`google.cloud.dialogflow_v2.types.Conversation`): + Required. The conversation to create. + This corresponds to the ``conversation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Conversation: + Represents a conversation. + A conversation is an interaction between + an agent, including live agents and + Dialogflow agents, and a support + customer. Conversations can include + phone calls and text-based chat + sessions. + + """ + # 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, conversation]) + if request is 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 = gcd_conversation.CreateConversationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if conversation is not None: + request.conversation = conversation + + # 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_conversation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_conversations(self, + request: Union[conversation.ListConversationsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListConversationsAsyncPager: + r"""Returns the list of all conversations in the + specified project. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListConversationsRequest, dict]): + The request object. The request message for + [Conversations.ListConversations][google.cloud.dialogflow.v2.Conversations.ListConversations]. + parent (:class:`str`): + Required. The project from which to list all + conversation. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.services.conversations.pagers.ListConversationsAsyncPager: + The response message for + [Conversations.ListConversations][google.cloud.dialogflow.v2.Conversations.ListConversations]. + + 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 = conversation.ListConversationsRequest(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_conversations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListConversationsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_conversation(self, + request: Union[conversation.GetConversationRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation.Conversation: + r"""Retrieves the specific conversation. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetConversationRequest, dict]): + The request object. The request message for + [Conversations.GetConversation][google.cloud.dialogflow.v2.Conversations.GetConversation]. + name (:class:`str`): + Required. The name of the conversation. Format: + ``projects//locations//conversations/``. + + 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.dialogflow_v2.types.Conversation: + Represents a conversation. + A conversation is an interaction between + an agent, including live agents and + Dialogflow agents, and a support + customer. Conversations can include + phone calls and text-based chat + sessions. + + """ + # 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 = conversation.GetConversationRequest(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_conversation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def complete_conversation(self, + request: Union[conversation.CompleteConversationRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation.Conversation: + r"""Completes the specified conversation. Finished + conversations are purged from the database after 30 + days. + + Args: + request (Union[google.cloud.dialogflow_v2.types.CompleteConversationRequest, dict]): + The request object. The request message for + [Conversations.CompleteConversation][google.cloud.dialogflow.v2.Conversations.CompleteConversation]. + name (:class:`str`): + Required. Resource identifier of the conversation to + close. Format: + ``projects//locations//conversations/``. + + 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.dialogflow_v2.types.Conversation: + Represents a conversation. + A conversation is an interaction between + an agent, including live agents and + Dialogflow agents, and a support + customer. Conversations can include + phone calls and text-based chat + sessions. + + """ + # 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 = conversation.CompleteConversationRequest(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.complete_conversation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_messages(self, + request: Union[conversation.ListMessagesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListMessagesAsyncPager: + r"""Lists messages that belong to a given conversation. ``messages`` + are ordered by ``create_time`` in descending order. To fetch + updates without duplication, send request with filter + ``create_time_epoch_microseconds > [first item's create_time of previous request]`` + and empty page_token. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListMessagesRequest, dict]): + The request object. The request message for + [Conversations.ListMessages][google.cloud.dialogflow.v2.Conversations.ListMessages]. + parent (:class:`str`): + Required. The name of the conversation to list messages + for. Format: + ``projects//locations//conversations/`` + + 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.dialogflow_v2.services.conversations.pagers.ListMessagesAsyncPager: + The response message for + [Conversations.ListMessages][google.cloud.dialogflow.v2.Conversations.ListMessages]. + + 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 = conversation.ListMessagesRequest(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_messages, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListMessagesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ConversationsAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/client.py new file mode 100644 index 000000000..5848c9c0b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/client.py @@ -0,0 +1,848 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2.services.conversations import pagers +from google.cloud.dialogflow_v2.types import conversation +from google.cloud.dialogflow_v2.types import conversation as gcd_conversation +from google.cloud.dialogflow_v2.types import participant +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ConversationsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ConversationsGrpcTransport +from .transports.grpc_asyncio import ConversationsGrpcAsyncIOTransport + + +class ConversationsClientMeta(type): + """Metaclass for the Conversations 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[ConversationsTransport]] + _transport_registry["grpc"] = ConversationsGrpcTransport + _transport_registry["grpc_asyncio"] = ConversationsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ConversationsTransport]: + """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 ConversationsClient(metaclass=ConversationsClientMeta): + """Service for managing + [Conversations][google.cloud.dialogflow.v2.Conversation]. + """ + + @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 = "dialogflow.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: + ConversationsClient: 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: + ConversationsClient: 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) -> ConversationsTransport: + """Returns the transport used by the client instance. + + Returns: + ConversationsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def conversation_path(project: str,conversation: str,) -> str: + """Returns a fully-qualified conversation string.""" + return "projects/{project}/conversations/{conversation}".format(project=project, conversation=conversation, ) + + @staticmethod + def parse_conversation_path(path: str) -> Dict[str,str]: + """Parses a conversation path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/conversations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def conversation_profile_path(project: str,conversation_profile: str,) -> str: + """Returns a fully-qualified conversation_profile string.""" + return "projects/{project}/conversationProfiles/{conversation_profile}".format(project=project, conversation_profile=conversation_profile, ) + + @staticmethod + def parse_conversation_profile_path(path: str) -> Dict[str,str]: + """Parses a conversation_profile path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/conversationProfiles/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def message_path(project: str,conversation: str,message: str,) -> str: + """Returns a fully-qualified message string.""" + return "projects/{project}/conversations/{conversation}/messages/{message}".format(project=project, conversation=conversation, message=message, ) + + @staticmethod + def parse_message_path(path: str) -> Dict[str,str]: + """Parses a message path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/conversations/(?P.+?)/messages/(?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, ConversationsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the conversations 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, ConversationsTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, ConversationsTransport): + # transport is a ConversationsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def create_conversation(self, + request: Union[gcd_conversation.CreateConversationRequest, dict] = None, + *, + parent: str = None, + conversation: gcd_conversation.Conversation = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_conversation.Conversation: + r"""Creates a new conversation. Conversations are auto-completed + after 24 hours. + + Conversation Lifecycle: There are two stages during a + conversation: Automated Agent Stage and Assist Stage. + + For Automated Agent Stage, there will be a dialogflow agent + responding to user queries. + + For Assist Stage, there's no dialogflow agent responding to user + queries. But we will provide suggestions which are generated + from conversation. + + If + [Conversation.conversation_profile][google.cloud.dialogflow.v2.Conversation.conversation_profile] + is configured for a dialogflow agent, conversation will start + from ``Automated Agent Stage``, otherwise, it will start from + ``Assist Stage``. And during ``Automated Agent Stage``, once an + [Intent][google.cloud.dialogflow.v2.Intent] with + [Intent.live_agent_handoff][google.cloud.dialogflow.v2.Intent.live_agent_handoff] + is triggered, conversation will transfer to Assist Stage. + + Args: + request (Union[google.cloud.dialogflow_v2.types.CreateConversationRequest, dict]): + The request object. The request message for + [Conversations.CreateConversation][google.cloud.dialogflow.v2.Conversations.CreateConversation]. + parent (str): + Required. Resource identifier of the project creating + the conversation. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + conversation (google.cloud.dialogflow_v2.types.Conversation): + Required. The conversation to create. + This corresponds to the ``conversation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Conversation: + Represents a conversation. + A conversation is an interaction between + an agent, including live agents and + Dialogflow agents, and a support + customer. Conversations can include + phone calls and text-based chat + sessions. + + """ + # 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, conversation]) + if request is 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 gcd_conversation.CreateConversationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_conversation.CreateConversationRequest): + request = gcd_conversation.CreateConversationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if conversation is not None: + request.conversation = conversation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_conversation] + + # Certain 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_conversations(self, + request: Union[conversation.ListConversationsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListConversationsPager: + r"""Returns the list of all conversations in the + specified project. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListConversationsRequest, dict]): + The request object. The request message for + [Conversations.ListConversations][google.cloud.dialogflow.v2.Conversations.ListConversations]. + parent (str): + Required. The project from which to list all + conversation. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.services.conversations.pagers.ListConversationsPager: + The response message for + [Conversations.ListConversations][google.cloud.dialogflow.v2.Conversations.ListConversations]. + + 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 conversation.ListConversationsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversation.ListConversationsRequest): + request = conversation.ListConversationsRequest(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_conversations] + + # Certain 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.ListConversationsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_conversation(self, + request: Union[conversation.GetConversationRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation.Conversation: + r"""Retrieves the specific conversation. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetConversationRequest, dict]): + The request object. The request message for + [Conversations.GetConversation][google.cloud.dialogflow.v2.Conversations.GetConversation]. + name (str): + Required. The name of the conversation. Format: + ``projects//locations//conversations/``. + + 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.dialogflow_v2.types.Conversation: + Represents a conversation. + A conversation is an interaction between + an agent, including live agents and + Dialogflow agents, and a support + customer. Conversations can include + phone calls and text-based chat + sessions. + + """ + # 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 conversation.GetConversationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversation.GetConversationRequest): + request = conversation.GetConversationRequest(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_conversation] + + # Certain 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 complete_conversation(self, + request: Union[conversation.CompleteConversationRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation.Conversation: + r"""Completes the specified conversation. Finished + conversations are purged from the database after 30 + days. + + Args: + request (Union[google.cloud.dialogflow_v2.types.CompleteConversationRequest, dict]): + The request object. The request message for + [Conversations.CompleteConversation][google.cloud.dialogflow.v2.Conversations.CompleteConversation]. + name (str): + Required. Resource identifier of the conversation to + close. Format: + ``projects//locations//conversations/``. + + 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.dialogflow_v2.types.Conversation: + Represents a conversation. + A conversation is an interaction between + an agent, including live agents and + Dialogflow agents, and a support + customer. Conversations can include + phone calls and text-based chat + sessions. + + """ + # 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 conversation.CompleteConversationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversation.CompleteConversationRequest): + request = conversation.CompleteConversationRequest(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.complete_conversation] + + # Certain 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_messages(self, + request: Union[conversation.ListMessagesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListMessagesPager: + r"""Lists messages that belong to a given conversation. ``messages`` + are ordered by ``create_time`` in descending order. To fetch + updates without duplication, send request with filter + ``create_time_epoch_microseconds > [first item's create_time of previous request]`` + and empty page_token. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListMessagesRequest, dict]): + The request object. The request message for + [Conversations.ListMessages][google.cloud.dialogflow.v2.Conversations.ListMessages]. + parent (str): + Required. The name of the conversation to list messages + for. Format: + ``projects//locations//conversations/`` + + 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.dialogflow_v2.services.conversations.pagers.ListMessagesPager: + The response message for + [Conversations.ListMessages][google.cloud.dialogflow.v2.Conversations.ListMessages]. + + 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 conversation.ListMessagesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversation.ListMessagesRequest): + request = conversation.ListMessagesRequest(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_messages] + + # Certain 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.ListMessagesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ConversationsClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/pagers.py new file mode 100644 index 000000000..18ff1402b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/pagers.py @@ -0,0 +1,263 @@ +# -*- 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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflow_v2.types import conversation +from google.cloud.dialogflow_v2.types import participant + + +class ListConversationsPager: + """A pager for iterating through ``list_conversations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListConversationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``conversations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListConversations`` requests and continue to iterate + through the ``conversations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListConversationsResponse` + 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[..., conversation.ListConversationsResponse], + request: conversation.ListConversationsRequest, + response: conversation.ListConversationsResponse, + *, + 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.dialogflow_v2.types.ListConversationsRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListConversationsResponse): + 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 = conversation.ListConversationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[conversation.ListConversationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[conversation.Conversation]: + for page in self.pages: + yield from page.conversations + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListConversationsAsyncPager: + """A pager for iterating through ``list_conversations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListConversationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``conversations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListConversations`` requests and continue to iterate + through the ``conversations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListConversationsResponse` + 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[conversation.ListConversationsResponse]], + request: conversation.ListConversationsRequest, + response: conversation.ListConversationsResponse, + *, + 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.dialogflow_v2.types.ListConversationsRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListConversationsResponse): + 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 = conversation.ListConversationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[conversation.ListConversationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[conversation.Conversation]: + async def async_generator(): + async for page in self.pages: + for response in page.conversations: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMessagesPager: + """A pager for iterating through ``list_messages`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListMessagesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``messages`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMessages`` requests and continue to iterate + through the ``messages`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListMessagesResponse` + 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[..., conversation.ListMessagesResponse], + request: conversation.ListMessagesRequest, + response: conversation.ListMessagesResponse, + *, + 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.dialogflow_v2.types.ListMessagesRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListMessagesResponse): + 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 = conversation.ListMessagesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[conversation.ListMessagesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[participant.Message]: + for page in self.pages: + yield from page.messages + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMessagesAsyncPager: + """A pager for iterating through ``list_messages`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListMessagesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``messages`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMessages`` requests and continue to iterate + through the ``messages`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListMessagesResponse` + 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[conversation.ListMessagesResponse]], + request: conversation.ListMessagesRequest, + response: conversation.ListMessagesResponse, + *, + 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.dialogflow_v2.types.ListMessagesRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListMessagesResponse): + 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 = conversation.ListMessagesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[conversation.ListMessagesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[participant.Message]: + async def async_generator(): + async for page in self.pages: + for response in page.messages: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/__init__.py new file mode 100644 index 000000000..9d9ee9030 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/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 ConversationsTransport +from .grpc import ConversationsGrpcTransport +from .grpc_asyncio import ConversationsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ConversationsTransport]] +_transport_registry['grpc'] = ConversationsGrpcTransport +_transport_registry['grpc_asyncio'] = ConversationsGrpcAsyncIOTransport + +__all__ = ( + 'ConversationsTransport', + 'ConversationsGrpcTransport', + 'ConversationsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/base.py new file mode 100644 index 000000000..8f77d0bdd --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/base.py @@ -0,0 +1,204 @@ +# -*- 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.types import conversation +from google.cloud.dialogflow_v2.types import conversation as gcd_conversation + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ConversationsTransport(abc.ABC): + """Abstract transport class for Conversations.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_conversation: gapic_v1.method.wrap_method( + self.create_conversation, + default_timeout=None, + client_info=client_info, + ), + self.list_conversations: gapic_v1.method.wrap_method( + self.list_conversations, + default_timeout=None, + client_info=client_info, + ), + self.get_conversation: gapic_v1.method.wrap_method( + self.get_conversation, + default_timeout=None, + client_info=client_info, + ), + self.complete_conversation: gapic_v1.method.wrap_method( + self.complete_conversation, + default_timeout=None, + client_info=client_info, + ), + self.list_messages: gapic_v1.method.wrap_method( + self.list_messages, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_conversation(self) -> Callable[ + [gcd_conversation.CreateConversationRequest], + Union[ + gcd_conversation.Conversation, + Awaitable[gcd_conversation.Conversation] + ]]: + raise NotImplementedError() + + @property + def list_conversations(self) -> Callable[ + [conversation.ListConversationsRequest], + Union[ + conversation.ListConversationsResponse, + Awaitable[conversation.ListConversationsResponse] + ]]: + raise NotImplementedError() + + @property + def get_conversation(self) -> Callable[ + [conversation.GetConversationRequest], + Union[ + conversation.Conversation, + Awaitable[conversation.Conversation] + ]]: + raise NotImplementedError() + + @property + def complete_conversation(self) -> Callable[ + [conversation.CompleteConversationRequest], + Union[ + conversation.Conversation, + Awaitable[conversation.Conversation] + ]]: + raise NotImplementedError() + + @property + def list_messages(self) -> Callable[ + [conversation.ListMessagesRequest], + Union[ + conversation.ListMessagesResponse, + Awaitable[conversation.ListMessagesResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'ConversationsTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/grpc.py new file mode 100644 index 000000000..7df36d034 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/grpc.py @@ -0,0 +1,387 @@ +# -*- 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 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import conversation +from google.cloud.dialogflow_v2.types import conversation as gcd_conversation +from .base import ConversationsTransport, DEFAULT_CLIENT_INFO + + +class ConversationsGrpcTransport(ConversationsTransport): + """gRPC backend transport for Conversations. + + Service for managing + [Conversations][google.cloud.dialogflow.v2.Conversation]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 = 'dialogflow.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_conversation(self) -> Callable[ + [gcd_conversation.CreateConversationRequest], + gcd_conversation.Conversation]: + r"""Return a callable for the create conversation method over gRPC. + + Creates a new conversation. Conversations are auto-completed + after 24 hours. + + Conversation Lifecycle: There are two stages during a + conversation: Automated Agent Stage and Assist Stage. + + For Automated Agent Stage, there will be a dialogflow agent + responding to user queries. + + For Assist Stage, there's no dialogflow agent responding to user + queries. But we will provide suggestions which are generated + from conversation. + + If + [Conversation.conversation_profile][google.cloud.dialogflow.v2.Conversation.conversation_profile] + is configured for a dialogflow agent, conversation will start + from ``Automated Agent Stage``, otherwise, it will start from + ``Assist Stage``. And during ``Automated Agent Stage``, once an + [Intent][google.cloud.dialogflow.v2.Intent] with + [Intent.live_agent_handoff][google.cloud.dialogflow.v2.Intent.live_agent_handoff] + is triggered, conversation will transfer to Assist Stage. + + Returns: + Callable[[~.CreateConversationRequest], + ~.Conversation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation' not in self._stubs: + self._stubs['create_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Conversations/CreateConversation', + request_serializer=gcd_conversation.CreateConversationRequest.serialize, + response_deserializer=gcd_conversation.Conversation.deserialize, + ) + return self._stubs['create_conversation'] + + @property + def list_conversations(self) -> Callable[ + [conversation.ListConversationsRequest], + conversation.ListConversationsResponse]: + r"""Return a callable for the list conversations method over gRPC. + + Returns the list of all conversations in the + specified project. + + Returns: + Callable[[~.ListConversationsRequest], + ~.ListConversationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversations' not in self._stubs: + self._stubs['list_conversations'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Conversations/ListConversations', + request_serializer=conversation.ListConversationsRequest.serialize, + response_deserializer=conversation.ListConversationsResponse.deserialize, + ) + return self._stubs['list_conversations'] + + @property + def get_conversation(self) -> Callable[ + [conversation.GetConversationRequest], + conversation.Conversation]: + r"""Return a callable for the get conversation method over gRPC. + + Retrieves the specific conversation. + + Returns: + Callable[[~.GetConversationRequest], + ~.Conversation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation' not in self._stubs: + self._stubs['get_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Conversations/GetConversation', + request_serializer=conversation.GetConversationRequest.serialize, + response_deserializer=conversation.Conversation.deserialize, + ) + return self._stubs['get_conversation'] + + @property + def complete_conversation(self) -> Callable[ + [conversation.CompleteConversationRequest], + conversation.Conversation]: + r"""Return a callable for the complete conversation method over gRPC. + + Completes the specified conversation. Finished + conversations are purged from the database after 30 + days. + + Returns: + Callable[[~.CompleteConversationRequest], + ~.Conversation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_conversation' not in self._stubs: + self._stubs['complete_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Conversations/CompleteConversation', + request_serializer=conversation.CompleteConversationRequest.serialize, + response_deserializer=conversation.Conversation.deserialize, + ) + return self._stubs['complete_conversation'] + + @property + def list_messages(self) -> Callable[ + [conversation.ListMessagesRequest], + conversation.ListMessagesResponse]: + r"""Return a callable for the list messages method over gRPC. + + Lists messages that belong to a given conversation. ``messages`` + are ordered by ``create_time`` in descending order. To fetch + updates without duplication, send request with filter + ``create_time_epoch_microseconds > [first item's create_time of previous request]`` + and empty page_token. + + Returns: + Callable[[~.ListMessagesRequest], + ~.ListMessagesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_messages' not in self._stubs: + self._stubs['list_messages'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Conversations/ListMessages', + request_serializer=conversation.ListMessagesRequest.serialize, + response_deserializer=conversation.ListMessagesResponse.deserialize, + ) + return self._stubs['list_messages'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'ConversationsGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/grpc_asyncio.py new file mode 100644 index 000000000..263c76b57 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/grpc_asyncio.py @@ -0,0 +1,391 @@ +# -*- 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 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import conversation +from google.cloud.dialogflow_v2.types import conversation as gcd_conversation +from .base import ConversationsTransport, DEFAULT_CLIENT_INFO +from .grpc import ConversationsGrpcTransport + + +class ConversationsGrpcAsyncIOTransport(ConversationsTransport): + """gRPC AsyncIO backend transport for Conversations. + + Service for managing + [Conversations][google.cloud.dialogflow.v2.Conversation]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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_conversation(self) -> Callable[ + [gcd_conversation.CreateConversationRequest], + Awaitable[gcd_conversation.Conversation]]: + r"""Return a callable for the create conversation method over gRPC. + + Creates a new conversation. Conversations are auto-completed + after 24 hours. + + Conversation Lifecycle: There are two stages during a + conversation: Automated Agent Stage and Assist Stage. + + For Automated Agent Stage, there will be a dialogflow agent + responding to user queries. + + For Assist Stage, there's no dialogflow agent responding to user + queries. But we will provide suggestions which are generated + from conversation. + + If + [Conversation.conversation_profile][google.cloud.dialogflow.v2.Conversation.conversation_profile] + is configured for a dialogflow agent, conversation will start + from ``Automated Agent Stage``, otherwise, it will start from + ``Assist Stage``. And during ``Automated Agent Stage``, once an + [Intent][google.cloud.dialogflow.v2.Intent] with + [Intent.live_agent_handoff][google.cloud.dialogflow.v2.Intent.live_agent_handoff] + is triggered, conversation will transfer to Assist Stage. + + Returns: + Callable[[~.CreateConversationRequest], + Awaitable[~.Conversation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation' not in self._stubs: + self._stubs['create_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Conversations/CreateConversation', + request_serializer=gcd_conversation.CreateConversationRequest.serialize, + response_deserializer=gcd_conversation.Conversation.deserialize, + ) + return self._stubs['create_conversation'] + + @property + def list_conversations(self) -> Callable[ + [conversation.ListConversationsRequest], + Awaitable[conversation.ListConversationsResponse]]: + r"""Return a callable for the list conversations method over gRPC. + + Returns the list of all conversations in the + specified project. + + Returns: + Callable[[~.ListConversationsRequest], + Awaitable[~.ListConversationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversations' not in self._stubs: + self._stubs['list_conversations'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Conversations/ListConversations', + request_serializer=conversation.ListConversationsRequest.serialize, + response_deserializer=conversation.ListConversationsResponse.deserialize, + ) + return self._stubs['list_conversations'] + + @property + def get_conversation(self) -> Callable[ + [conversation.GetConversationRequest], + Awaitable[conversation.Conversation]]: + r"""Return a callable for the get conversation method over gRPC. + + Retrieves the specific conversation. + + Returns: + Callable[[~.GetConversationRequest], + Awaitable[~.Conversation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation' not in self._stubs: + self._stubs['get_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Conversations/GetConversation', + request_serializer=conversation.GetConversationRequest.serialize, + response_deserializer=conversation.Conversation.deserialize, + ) + return self._stubs['get_conversation'] + + @property + def complete_conversation(self) -> Callable[ + [conversation.CompleteConversationRequest], + Awaitable[conversation.Conversation]]: + r"""Return a callable for the complete conversation method over gRPC. + + Completes the specified conversation. Finished + conversations are purged from the database after 30 + days. + + Returns: + Callable[[~.CompleteConversationRequest], + Awaitable[~.Conversation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_conversation' not in self._stubs: + self._stubs['complete_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Conversations/CompleteConversation', + request_serializer=conversation.CompleteConversationRequest.serialize, + response_deserializer=conversation.Conversation.deserialize, + ) + return self._stubs['complete_conversation'] + + @property + def list_messages(self) -> Callable[ + [conversation.ListMessagesRequest], + Awaitable[conversation.ListMessagesResponse]]: + r"""Return a callable for the list messages method over gRPC. + + Lists messages that belong to a given conversation. ``messages`` + are ordered by ``create_time`` in descending order. To fetch + updates without duplication, send request with filter + ``create_time_epoch_microseconds > [first item's create_time of previous request]`` + and empty page_token. + + Returns: + Callable[[~.ListMessagesRequest], + Awaitable[~.ListMessagesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_messages' not in self._stubs: + self._stubs['list_messages'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Conversations/ListMessages', + request_serializer=conversation.ListMessagesRequest.serialize, + response_deserializer=conversation.ListMessagesResponse.deserialize, + ) + return self._stubs['list_messages'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ConversationsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/__init__.py new file mode 100644 index 000000000..cee70ad81 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/__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 DocumentsClient +from .async_client import DocumentsAsyncClient + +__all__ = ( + 'DocumentsClient', + 'DocumentsAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/async_client.py new file mode 100644 index 000000000..287caaa31 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/async_client.py @@ -0,0 +1,885 @@ +# -*- 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 + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.dialogflow_v2.services.documents import pagers +from google.cloud.dialogflow_v2.types import document +from google.cloud.dialogflow_v2.types import document as gcd_document +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import DocumentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DocumentsGrpcAsyncIOTransport +from .client import DocumentsClient + + +class DocumentsAsyncClient: + """Service for managing knowledge + [Documents][google.cloud.dialogflow.v2.Document]. + """ + + _client: DocumentsClient + + DEFAULT_ENDPOINT = DocumentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DocumentsClient.DEFAULT_MTLS_ENDPOINT + + document_path = staticmethod(DocumentsClient.document_path) + parse_document_path = staticmethod(DocumentsClient.parse_document_path) + common_billing_account_path = staticmethod(DocumentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DocumentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DocumentsClient.common_folder_path) + parse_common_folder_path = staticmethod(DocumentsClient.parse_common_folder_path) + common_organization_path = staticmethod(DocumentsClient.common_organization_path) + parse_common_organization_path = staticmethod(DocumentsClient.parse_common_organization_path) + common_project_path = staticmethod(DocumentsClient.common_project_path) + parse_common_project_path = staticmethod(DocumentsClient.parse_common_project_path) + common_location_path = staticmethod(DocumentsClient.common_location_path) + parse_common_location_path = staticmethod(DocumentsClient.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: + DocumentsAsyncClient: The constructed client. + """ + return DocumentsClient.from_service_account_info.__func__(DocumentsAsyncClient, 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: + DocumentsAsyncClient: The constructed client. + """ + return DocumentsClient.from_service_account_file.__func__(DocumentsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> DocumentsTransport: + """Returns the transport used by the client instance. + + Returns: + DocumentsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(DocumentsClient).get_transport_class, type(DocumentsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, DocumentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the documents 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, ~.DocumentsTransport]): 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 = DocumentsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_documents(self, + request: Union[document.ListDocumentsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDocumentsAsyncPager: + r"""Returns the list of all documents of the knowledge + base. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListDocumentsRequest, dict]): + The request object. Request message for + [Documents.ListDocuments][google.cloud.dialogflow.v2.Documents.ListDocuments]. + parent (:class:`str`): + Required. The knowledge base to list all documents for. + Format: + ``projects//locations//knowledgeBases/``. + + 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.dialogflow_v2.services.documents.pagers.ListDocumentsAsyncPager: + Response message for + [Documents.ListDocuments][google.cloud.dialogflow.v2.Documents.ListDocuments]. + + 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 = document.ListDocumentsRequest(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_documents, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDocumentsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_document(self, + request: Union[document.GetDocumentRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document.Document: + r"""Retrieves the specified document. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetDocumentRequest, dict]): + The request object. Request message for + [Documents.GetDocument][google.cloud.dialogflow.v2.Documents.GetDocument]. + name (:class:`str`): + Required. The name of the document to retrieve. Format + ``projects//locations//knowledgeBases//documents/``. + + 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.dialogflow_v2.types.Document: + A knowledge document to be used by a + [KnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBase]. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases.documents + resource is deprecated; only use + projects.knowledgeBases.documents. + + """ + # 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 = document.GetDocumentRequest(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_document, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_document(self, + request: Union[gcd_document.CreateDocumentRequest, dict] = None, + *, + parent: str = None, + document: gcd_document.Document = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new document. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] + - ``response``: [Document][google.cloud.dialogflow.v2.Document] + + Args: + request (Union[google.cloud.dialogflow_v2.types.CreateDocumentRequest, dict]): + The request object. Request message for + [Documents.CreateDocument][google.cloud.dialogflow.v2.Documents.CreateDocument]. + parent (:class:`str`): + Required. The knowledge base to create a document for. + Format: + ``projects//locations//knowledgeBases/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + document (:class:`google.cloud.dialogflow_v2.types.Document`): + Required. The document to create. + This corresponds to the ``document`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.dialogflow_v2.types.Document` A + knowledge document to be used by a + [KnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBase]. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases.documents + resource is deprecated; only use + projects.knowledgeBases.documents. + + """ + # 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, document]) + if request is 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 = gcd_document.CreateDocumentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if document is not None: + request.document = document + + # 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_document, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcd_document.Document, + metadata_type=gcd_document.KnowledgeOperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_document(self, + request: Union[document.DeleteDocumentRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes the specified document. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] + - ``response``: An `Empty + message `__ + + Args: + request (Union[google.cloud.dialogflow_v2.types.DeleteDocumentRequest, dict]): + The request object. Request message for + [Documents.DeleteDocument][google.cloud.dialogflow.v2.Documents.DeleteDocument]. + name (:class:`str`): + Required. The name of the document to delete. Format: + ``projects//locations//knowledgeBases//documents/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = document.DeleteDocumentRequest(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_document, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=document.KnowledgeOperationMetadata, + ) + + # Done; return the response. + return response + + async def update_document(self, + request: Union[gcd_document.UpdateDocumentRequest, dict] = None, + *, + document: gcd_document.Document = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the specified document. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] + - ``response``: [Document][google.cloud.dialogflow.v2.Document] + + Args: + request (Union[google.cloud.dialogflow_v2.types.UpdateDocumentRequest, dict]): + The request object. Request message for + [Documents.UpdateDocument][google.cloud.dialogflow.v2.Documents.UpdateDocument]. + document (:class:`google.cloud.dialogflow_v2.types.Document`): + Required. The document to update. + This corresponds to the ``document`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Not specified means ``update all``. Currently, + only ``display_name`` can be updated, an InvalidArgument + will be returned for attempting to update other 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflow_v2.types.Document` A + knowledge document to be used by a + [KnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBase]. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases.documents + resource is deprecated; only use + projects.knowledgeBases.documents. + + """ + # 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([document, 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 = gcd_document.UpdateDocumentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if document is not None: + request.document = document + 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_document, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("document.name", request.document.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcd_document.Document, + metadata_type=gcd_document.KnowledgeOperationMetadata, + ) + + # Done; return the response. + return response + + async def reload_document(self, + request: Union[document.ReloadDocumentRequest, dict] = None, + *, + name: str = None, + content_uri: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Reloads the specified document from its specified source, + content_uri or content. The previously loaded content of the + document will be deleted. Note: Even when the content of the + document has not changed, there still may be side effects + because of internal implementation changes. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] + - ``response``: [Document][google.cloud.dialogflow.v2.Document] + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ReloadDocumentRequest, dict]): + The request object. Request message for + [Documents.ReloadDocument][google.cloud.dialogflow.v2.Documents.ReloadDocument]. + name (:class:`str`): + Required. The name of the document to reload. Format: + ``projects//locations//knowledgeBases//documents/`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + content_uri (:class:`str`): + Optional. The path of gcs source file for reloading + document content. For now, only gcs uri is supported. + + For documents stored in Google Cloud Storage, these URIs + must have the form ``gs:///``. + + This corresponds to the ``content_uri`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.dialogflow_v2.types.Document` A + knowledge document to be used by a + [KnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBase]. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases.documents + resource is deprecated; only use + projects.knowledgeBases.documents. + + """ + # 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, content_uri]) + if request is 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 = document.ReloadDocumentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if content_uri is not None: + request.content_uri = content_uri + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.reload_document, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + document.Document, + metadata_type=document.KnowledgeOperationMetadata, + ) + + # Done; return the response. + return response + + async def export_document(self, + request: Union[document.ExportDocumentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Exports a smart messaging candidate document into the specified + destination. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] + - ``response``: [Document][google.cloud.dialogflow.v2.Document] + + Args: + request (Union[google.cloud.dialogflow_v2.types.ExportDocumentRequest, dict]): + The request object. Request message for + [Documents.ExportDocument][google.cloud.dialogflow.v2.Documents.ExportDocument]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.dialogflow_v2.types.Document` A + knowledge document to be used by a + [KnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBase]. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases.documents + resource is deprecated; only use + projects.knowledgeBases.documents. + + """ + # Create or coerce a protobuf request object. + request = document.ExportDocumentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.export_document, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + document.Document, + metadata_type=document.KnowledgeOperationMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "DocumentsAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/client.py new file mode 100644 index 000000000..681c80ef0 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/client.py @@ -0,0 +1,1084 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.dialogflow_v2.services.documents import pagers +from google.cloud.dialogflow_v2.types import document +from google.cloud.dialogflow_v2.types import document as gcd_document +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import DocumentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DocumentsGrpcTransport +from .transports.grpc_asyncio import DocumentsGrpcAsyncIOTransport + + +class DocumentsClientMeta(type): + """Metaclass for the Documents 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[DocumentsTransport]] + _transport_registry["grpc"] = DocumentsGrpcTransport + _transport_registry["grpc_asyncio"] = DocumentsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[DocumentsTransport]: + """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 DocumentsClient(metaclass=DocumentsClientMeta): + """Service for managing knowledge + [Documents][google.cloud.dialogflow.v2.Document]. + """ + + @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 = "dialogflow.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: + DocumentsClient: 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: + DocumentsClient: 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) -> DocumentsTransport: + """Returns the transport used by the client instance. + + Returns: + DocumentsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def document_path(project: str,knowledge_base: str,document: str,) -> str: + """Returns a fully-qualified document string.""" + return "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format(project=project, knowledge_base=knowledge_base, document=document, ) + + @staticmethod + def parse_document_path(path: str) -> Dict[str,str]: + """Parses a document path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/knowledgeBases/(?P.+?)/documents/(?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, DocumentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the documents 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, DocumentsTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, DocumentsTransport): + # transport is a DocumentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_documents(self, + request: Union[document.ListDocumentsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDocumentsPager: + r"""Returns the list of all documents of the knowledge + base. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListDocumentsRequest, dict]): + The request object. Request message for + [Documents.ListDocuments][google.cloud.dialogflow.v2.Documents.ListDocuments]. + parent (str): + Required. The knowledge base to list all documents for. + Format: + ``projects//locations//knowledgeBases/``. + + 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.dialogflow_v2.services.documents.pagers.ListDocumentsPager: + Response message for + [Documents.ListDocuments][google.cloud.dialogflow.v2.Documents.ListDocuments]. + + 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 document.ListDocumentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document.ListDocumentsRequest): + request = document.ListDocumentsRequest(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_documents] + + # Certain 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.ListDocumentsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_document(self, + request: Union[document.GetDocumentRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document.Document: + r"""Retrieves the specified document. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetDocumentRequest, dict]): + The request object. Request message for + [Documents.GetDocument][google.cloud.dialogflow.v2.Documents.GetDocument]. + name (str): + Required. The name of the document to retrieve. Format + ``projects//locations//knowledgeBases//documents/``. + + 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.dialogflow_v2.types.Document: + A knowledge document to be used by a + [KnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBase]. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases.documents + resource is deprecated; only use + projects.knowledgeBases.documents. + + """ + # 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 document.GetDocumentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document.GetDocumentRequest): + request = document.GetDocumentRequest(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_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_document(self, + request: Union[gcd_document.CreateDocumentRequest, dict] = None, + *, + parent: str = None, + document: gcd_document.Document = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new document. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] + - ``response``: [Document][google.cloud.dialogflow.v2.Document] + + Args: + request (Union[google.cloud.dialogflow_v2.types.CreateDocumentRequest, dict]): + The request object. Request message for + [Documents.CreateDocument][google.cloud.dialogflow.v2.Documents.CreateDocument]. + parent (str): + Required. The knowledge base to create a document for. + Format: + ``projects//locations//knowledgeBases/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + document (google.cloud.dialogflow_v2.types.Document): + Required. The document to create. + This corresponds to the ``document`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.dialogflow_v2.types.Document` A + knowledge document to be used by a + [KnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBase]. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases.documents + resource is deprecated; only use + projects.knowledgeBases.documents. + + """ + # 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, document]) + if request is 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 gcd_document.CreateDocumentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_document.CreateDocumentRequest): + request = gcd_document.CreateDocumentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if document is not None: + request.document = document + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_document] + + # Certain 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, + gcd_document.Document, + metadata_type=gcd_document.KnowledgeOperationMetadata, + ) + + # Done; return the response. + return response + + def delete_document(self, + request: Union[document.DeleteDocumentRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes the specified document. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] + - ``response``: An `Empty + message `__ + + Args: + request (Union[google.cloud.dialogflow_v2.types.DeleteDocumentRequest, dict]): + The request object. Request message for + [Documents.DeleteDocument][google.cloud.dialogflow.v2.Documents.DeleteDocument]. + name (str): + Required. The name of the document to delete. Format: + ``projects//locations//knowledgeBases//documents/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a document.DeleteDocumentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document.DeleteDocumentRequest): + request = document.DeleteDocumentRequest(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_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=document.KnowledgeOperationMetadata, + ) + + # Done; return the response. + return response + + def update_document(self, + request: Union[gcd_document.UpdateDocumentRequest, dict] = None, + *, + document: gcd_document.Document = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the specified document. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] + - ``response``: [Document][google.cloud.dialogflow.v2.Document] + + Args: + request (Union[google.cloud.dialogflow_v2.types.UpdateDocumentRequest, dict]): + The request object. Request message for + [Documents.UpdateDocument][google.cloud.dialogflow.v2.Documents.UpdateDocument]. + document (google.cloud.dialogflow_v2.types.Document): + Required. The document to update. + This corresponds to the ``document`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Not specified means ``update all``. Currently, + only ``display_name`` can be updated, an InvalidArgument + will be returned for attempting to update other 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflow_v2.types.Document` A + knowledge document to be used by a + [KnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBase]. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases.documents + resource is deprecated; only use + projects.knowledgeBases.documents. + + """ + # 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([document, 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 gcd_document.UpdateDocumentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_document.UpdateDocumentRequest): + request = gcd_document.UpdateDocumentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if document is not None: + request.document = document + 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_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("document.name", request.document.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcd_document.Document, + metadata_type=gcd_document.KnowledgeOperationMetadata, + ) + + # Done; return the response. + return response + + def reload_document(self, + request: Union[document.ReloadDocumentRequest, dict] = None, + *, + name: str = None, + content_uri: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Reloads the specified document from its specified source, + content_uri or content. The previously loaded content of the + document will be deleted. Note: Even when the content of the + document has not changed, there still may be side effects + because of internal implementation changes. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] + - ``response``: [Document][google.cloud.dialogflow.v2.Document] + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ReloadDocumentRequest, dict]): + The request object. Request message for + [Documents.ReloadDocument][google.cloud.dialogflow.v2.Documents.ReloadDocument]. + name (str): + Required. The name of the document to reload. Format: + ``projects//locations//knowledgeBases//documents/`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + content_uri (str): + Optional. The path of gcs source file for reloading + document content. For now, only gcs uri is supported. + + For documents stored in Google Cloud Storage, these URIs + must have the form ``gs:///``. + + This corresponds to the ``content_uri`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.dialogflow_v2.types.Document` A + knowledge document to be used by a + [KnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBase]. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases.documents + resource is deprecated; only use + projects.knowledgeBases.documents. + + """ + # 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, content_uri]) + if request is 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 document.ReloadDocumentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document.ReloadDocumentRequest): + request = document.ReloadDocumentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if content_uri is not None: + request.content_uri = content_uri + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.reload_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + document.Document, + metadata_type=document.KnowledgeOperationMetadata, + ) + + # Done; return the response. + return response + + def export_document(self, + request: Union[document.ExportDocumentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Exports a smart messaging candidate document into the specified + destination. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] + - ``response``: [Document][google.cloud.dialogflow.v2.Document] + + Args: + request (Union[google.cloud.dialogflow_v2.types.ExportDocumentRequest, dict]): + The request object. Request message for + [Documents.ExportDocument][google.cloud.dialogflow.v2.Documents.ExportDocument]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.dialogflow_v2.types.Document` A + knowledge document to be used by a + [KnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBase]. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases.documents + resource is deprecated; only use + projects.knowledgeBases.documents. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a document.ExportDocumentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document.ExportDocumentRequest): + request = document.ExportDocumentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.export_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + document.Document, + metadata_type=document.KnowledgeOperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "DocumentsClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/pagers.py new file mode 100644 index 000000000..3d5b464a4 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflow_v2.types import document + + +class ListDocumentsPager: + """A pager for iterating through ``list_documents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListDocumentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``documents`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDocuments`` requests and continue to iterate + through the ``documents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListDocumentsResponse` + 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[..., document.ListDocumentsResponse], + request: document.ListDocumentsRequest, + response: document.ListDocumentsResponse, + *, + 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.dialogflow_v2.types.ListDocumentsRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListDocumentsResponse): + 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 = document.ListDocumentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[document.ListDocumentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[document.Document]: + for page in self.pages: + yield from page.documents + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDocumentsAsyncPager: + """A pager for iterating through ``list_documents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListDocumentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``documents`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDocuments`` requests and continue to iterate + through the ``documents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListDocumentsResponse` + 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[document.ListDocumentsResponse]], + request: document.ListDocumentsRequest, + response: document.ListDocumentsResponse, + *, + 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.dialogflow_v2.types.ListDocumentsRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListDocumentsResponse): + 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 = document.ListDocumentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[document.ListDocumentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[document.Document]: + async def async_generator(): + async for page in self.pages: + for response in page.documents: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/__init__.py new file mode 100644 index 000000000..f9ae67be5 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/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 DocumentsTransport +from .grpc import DocumentsGrpcTransport +from .grpc_asyncio import DocumentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DocumentsTransport]] +_transport_registry['grpc'] = DocumentsGrpcTransport +_transport_registry['grpc_asyncio'] = DocumentsGrpcAsyncIOTransport + +__all__ = ( + 'DocumentsTransport', + 'DocumentsGrpcTransport', + 'DocumentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/base.py new file mode 100644 index 000000000..ecdc8e8df --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/base.py @@ -0,0 +1,239 @@ +# -*- 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.types import document +from google.cloud.dialogflow_v2.types import document as gcd_document +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-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class DocumentsTransport(abc.ABC): + """Abstract transport class for Documents.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_documents: gapic_v1.method.wrap_method( + self.list_documents, + default_timeout=None, + client_info=client_info, + ), + self.get_document: gapic_v1.method.wrap_method( + self.get_document, + default_timeout=None, + client_info=client_info, + ), + self.create_document: gapic_v1.method.wrap_method( + self.create_document, + default_timeout=None, + client_info=client_info, + ), + self.delete_document: gapic_v1.method.wrap_method( + self.delete_document, + default_timeout=None, + client_info=client_info, + ), + self.update_document: gapic_v1.method.wrap_method( + self.update_document, + default_timeout=None, + client_info=client_info, + ), + self.reload_document: gapic_v1.method.wrap_method( + self.reload_document, + default_timeout=None, + client_info=client_info, + ), + self.export_document: gapic_v1.method.wrap_method( + self.export_document, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_documents(self) -> Callable[ + [document.ListDocumentsRequest], + Union[ + document.ListDocumentsResponse, + Awaitable[document.ListDocumentsResponse] + ]]: + raise NotImplementedError() + + @property + def get_document(self) -> Callable[ + [document.GetDocumentRequest], + Union[ + document.Document, + Awaitable[document.Document] + ]]: + raise NotImplementedError() + + @property + def create_document(self) -> Callable[ + [gcd_document.CreateDocumentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_document(self) -> Callable[ + [document.DeleteDocumentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_document(self) -> Callable[ + [gcd_document.UpdateDocumentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def reload_document(self) -> Callable[ + [document.ReloadDocumentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def export_document(self) -> Callable[ + [document.ExportDocumentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'DocumentsTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/grpc.py new file mode 100644 index 000000000..1dd738921 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/grpc.py @@ -0,0 +1,486 @@ +# -*- 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 +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import document +from google.cloud.dialogflow_v2.types import document as gcd_document +from google.longrunning import operations_pb2 # type: ignore +from .base import DocumentsTransport, DEFAULT_CLIENT_INFO + + +class DocumentsGrpcTransport(DocumentsTransport): + """gRPC backend transport for Documents. + + Service for managing knowledge + [Documents][google.cloud.dialogflow.v2.Document]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 = 'dialogflow.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 list_documents(self) -> Callable[ + [document.ListDocumentsRequest], + document.ListDocumentsResponse]: + r"""Return a callable for the list documents method over gRPC. + + Returns the list of all documents of the knowledge + base. + + Returns: + Callable[[~.ListDocumentsRequest], + ~.ListDocumentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_documents' not in self._stubs: + self._stubs['list_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Documents/ListDocuments', + request_serializer=document.ListDocumentsRequest.serialize, + response_deserializer=document.ListDocumentsResponse.deserialize, + ) + return self._stubs['list_documents'] + + @property + def get_document(self) -> Callable[ + [document.GetDocumentRequest], + document.Document]: + r"""Return a callable for the get document method over gRPC. + + Retrieves the specified document. + + Returns: + Callable[[~.GetDocumentRequest], + ~.Document]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['get_document'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Documents/GetDocument', + request_serializer=document.GetDocumentRequest.serialize, + response_deserializer=document.Document.deserialize, + ) + return self._stubs['get_document'] + + @property + def create_document(self) -> Callable[ + [gcd_document.CreateDocumentRequest], + operations_pb2.Operation]: + r"""Return a callable for the create document method over gRPC. + + Creates a new document. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] + - ``response``: [Document][google.cloud.dialogflow.v2.Document] + + Returns: + Callable[[~.CreateDocumentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['create_document'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Documents/CreateDocument', + request_serializer=gcd_document.CreateDocumentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_document'] + + @property + def delete_document(self) -> Callable[ + [document.DeleteDocumentRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete document method over gRPC. + + Deletes the specified document. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] + - ``response``: An `Empty + message `__ + + Returns: + Callable[[~.DeleteDocumentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['delete_document'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Documents/DeleteDocument', + request_serializer=document.DeleteDocumentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_document'] + + @property + def update_document(self) -> Callable[ + [gcd_document.UpdateDocumentRequest], + operations_pb2.Operation]: + r"""Return a callable for the update document method over gRPC. + + Updates the specified document. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] + - ``response``: [Document][google.cloud.dialogflow.v2.Document] + + Returns: + Callable[[~.UpdateDocumentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['update_document'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Documents/UpdateDocument', + request_serializer=gcd_document.UpdateDocumentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_document'] + + @property + def reload_document(self) -> Callable[ + [document.ReloadDocumentRequest], + operations_pb2.Operation]: + r"""Return a callable for the reload document method over gRPC. + + Reloads the specified document from its specified source, + content_uri or content. The previously loaded content of the + document will be deleted. Note: Even when the content of the + document has not changed, there still may be side effects + because of internal implementation changes. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] + - ``response``: [Document][google.cloud.dialogflow.v2.Document] + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Returns: + Callable[[~.ReloadDocumentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'reload_document' not in self._stubs: + self._stubs['reload_document'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Documents/ReloadDocument', + request_serializer=document.ReloadDocumentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['reload_document'] + + @property + def export_document(self) -> Callable[ + [document.ExportDocumentRequest], + operations_pb2.Operation]: + r"""Return a callable for the export document method over gRPC. + + Exports a smart messaging candidate document into the specified + destination. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] + - ``response``: [Document][google.cloud.dialogflow.v2.Document] + + Returns: + Callable[[~.ExportDocumentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'export_document' not in self._stubs: + self._stubs['export_document'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Documents/ExportDocument', + request_serializer=document.ExportDocumentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_document'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'DocumentsGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/grpc_asyncio.py new file mode 100644 index 000000000..828b3dfbc --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/grpc_asyncio.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. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import document +from google.cloud.dialogflow_v2.types import document as gcd_document +from google.longrunning import operations_pb2 # type: ignore +from .base import DocumentsTransport, DEFAULT_CLIENT_INFO +from .grpc import DocumentsGrpcTransport + + +class DocumentsGrpcAsyncIOTransport(DocumentsTransport): + """gRPC AsyncIO backend transport for Documents. + + Service for managing knowledge + [Documents][google.cloud.dialogflow.v2.Document]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 list_documents(self) -> Callable[ + [document.ListDocumentsRequest], + Awaitable[document.ListDocumentsResponse]]: + r"""Return a callable for the list documents method over gRPC. + + Returns the list of all documents of the knowledge + base. + + Returns: + Callable[[~.ListDocumentsRequest], + Awaitable[~.ListDocumentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_documents' not in self._stubs: + self._stubs['list_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Documents/ListDocuments', + request_serializer=document.ListDocumentsRequest.serialize, + response_deserializer=document.ListDocumentsResponse.deserialize, + ) + return self._stubs['list_documents'] + + @property + def get_document(self) -> Callable[ + [document.GetDocumentRequest], + Awaitable[document.Document]]: + r"""Return a callable for the get document method over gRPC. + + Retrieves the specified document. + + Returns: + Callable[[~.GetDocumentRequest], + Awaitable[~.Document]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['get_document'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Documents/GetDocument', + request_serializer=document.GetDocumentRequest.serialize, + response_deserializer=document.Document.deserialize, + ) + return self._stubs['get_document'] + + @property + def create_document(self) -> Callable[ + [gcd_document.CreateDocumentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create document method over gRPC. + + Creates a new document. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] + - ``response``: [Document][google.cloud.dialogflow.v2.Document] + + Returns: + Callable[[~.CreateDocumentRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_document' not in self._stubs: + self._stubs['create_document'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Documents/CreateDocument', + request_serializer=gcd_document.CreateDocumentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_document'] + + @property + def delete_document(self) -> Callable[ + [document.DeleteDocumentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete document method over gRPC. + + Deletes the specified document. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] + - ``response``: An `Empty + message `__ + + Returns: + Callable[[~.DeleteDocumentRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_document' not in self._stubs: + self._stubs['delete_document'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Documents/DeleteDocument', + request_serializer=document.DeleteDocumentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_document'] + + @property + def update_document(self) -> Callable[ + [gcd_document.UpdateDocumentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update document method over gRPC. + + Updates the specified document. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] + - ``response``: [Document][google.cloud.dialogflow.v2.Document] + + Returns: + Callable[[~.UpdateDocumentRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_document' not in self._stubs: + self._stubs['update_document'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Documents/UpdateDocument', + request_serializer=gcd_document.UpdateDocumentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_document'] + + @property + def reload_document(self) -> Callable[ + [document.ReloadDocumentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the reload document method over gRPC. + + Reloads the specified document from its specified source, + content_uri or content. The previously loaded content of the + document will be deleted. Note: Even when the content of the + document has not changed, there still may be side effects + because of internal implementation changes. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] + - ``response``: [Document][google.cloud.dialogflow.v2.Document] + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Returns: + Callable[[~.ReloadDocumentRequest], + 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 'reload_document' not in self._stubs: + self._stubs['reload_document'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Documents/ReloadDocument', + request_serializer=document.ReloadDocumentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['reload_document'] + + @property + def export_document(self) -> Callable[ + [document.ExportDocumentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the export document method over gRPC. + + Exports a smart messaging candidate document into the specified + destination. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] + - ``response``: [Document][google.cloud.dialogflow.v2.Document] + + Returns: + Callable[[~.ExportDocumentRequest], + 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 'export_document' not in self._stubs: + self._stubs['export_document'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Documents/ExportDocument', + request_serializer=document.ExportDocumentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_document'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'DocumentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/__init__.py new file mode 100644 index 000000000..82dfe86fd --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/__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 EntityTypesClient +from .async_client import EntityTypesAsyncClient + +__all__ = ( + 'EntityTypesClient', + 'EntityTypesAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/async_client.py new file mode 100644 index 000000000..492d9e76f --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/async_client.py @@ -0,0 +1,1269 @@ +# -*- 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 + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.dialogflow_v2.services.entity_types import pagers +from google.cloud.dialogflow_v2.types import entity_type +from google.cloud.dialogflow_v2.types import entity_type as gcd_entity_type +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import EntityTypesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import EntityTypesGrpcAsyncIOTransport +from .client import EntityTypesClient + + +class EntityTypesAsyncClient: + """Service for managing + [EntityTypes][google.cloud.dialogflow.v2.EntityType]. + """ + + _client: EntityTypesClient + + DEFAULT_ENDPOINT = EntityTypesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = EntityTypesClient.DEFAULT_MTLS_ENDPOINT + + entity_type_path = staticmethod(EntityTypesClient.entity_type_path) + parse_entity_type_path = staticmethod(EntityTypesClient.parse_entity_type_path) + common_billing_account_path = staticmethod(EntityTypesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(EntityTypesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(EntityTypesClient.common_folder_path) + parse_common_folder_path = staticmethod(EntityTypesClient.parse_common_folder_path) + common_organization_path = staticmethod(EntityTypesClient.common_organization_path) + parse_common_organization_path = staticmethod(EntityTypesClient.parse_common_organization_path) + common_project_path = staticmethod(EntityTypesClient.common_project_path) + parse_common_project_path = staticmethod(EntityTypesClient.parse_common_project_path) + common_location_path = staticmethod(EntityTypesClient.common_location_path) + parse_common_location_path = staticmethod(EntityTypesClient.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: + EntityTypesAsyncClient: The constructed client. + """ + return EntityTypesClient.from_service_account_info.__func__(EntityTypesAsyncClient, 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: + EntityTypesAsyncClient: The constructed client. + """ + return EntityTypesClient.from_service_account_file.__func__(EntityTypesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> EntityTypesTransport: + """Returns the transport used by the client instance. + + Returns: + EntityTypesTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(EntityTypesClient).get_transport_class, type(EntityTypesClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, EntityTypesTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the entity types 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, ~.EntityTypesTransport]): 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 = EntityTypesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_entity_types(self, + request: Union[entity_type.ListEntityTypesRequest, dict] = None, + *, + parent: str = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEntityTypesAsyncPager: + r"""Returns the list of all entity types in the specified + agent. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListEntityTypesRequest, dict]): + The request object. The request message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2.EntityTypes.ListEntityTypes]. + parent (:class:`str`): + Required. The agent to list all entity types from. + Format: ``projects//agent``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (:class:`str`): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.services.entity_types.pagers.ListEntityTypesAsyncPager: + The response message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2.EntityTypes.ListEntityTypes]. + + 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, language_code]) + if request is 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 = entity_type.ListEntityTypesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if language_code is not None: + request.language_code = language_code + + # 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_entity_types, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEntityTypesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_entity_type(self, + request: Union[entity_type.GetEntityTypeRequest, dict] = None, + *, + name: str = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> entity_type.EntityType: + r"""Retrieves the specified entity type. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetEntityTypeRequest, dict]): + The request object. The request message for + [EntityTypes.GetEntityType][google.cloud.dialogflow.v2.EntityTypes.GetEntityType]. + name (:class:`str`): + Required. The name of the entity type. Format: + ``projects//agent/entityTypes/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (:class:`str`): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.EntityType: + Each intent parameter has a type, called the entity type, which dictates + exactly how data from an end-user expression is + extracted. + + Dialogflow provides predefined system entities that + can match many common types of data. For example, + there are system entities for matching dates, times, + colors, email addresses, and so on. You can also + create your own custom entities for matching custom + data. For example, you could define a vegetable + entity that can match the types of vegetables + available for purchase with a grocery store agent. + + For more information, see the [Entity + guide](\ https://cloud.google.com/dialogflow/docs/entities-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, language_code]) + if request is 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 = entity_type.GetEntityTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if language_code is not None: + request.language_code = language_code + + # 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_entity_type, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_entity_type(self, + request: Union[gcd_entity_type.CreateEntityTypeRequest, dict] = None, + *, + parent: str = None, + entity_type: gcd_entity_type.EntityType = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_entity_type.EntityType: + r"""Creates an entity type in the specified agent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.CreateEntityTypeRequest, dict]): + The request object. The request message for + [EntityTypes.CreateEntityType][google.cloud.dialogflow.v2.EntityTypes.CreateEntityType]. + parent (:class:`str`): + Required. The agent to create a entity type for. Format: + ``projects//agent``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entity_type (:class:`google.cloud.dialogflow_v2.types.EntityType`): + Required. The entity type to create. + This corresponds to the ``entity_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (:class:`str`): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.EntityType: + Each intent parameter has a type, called the entity type, which dictates + exactly how data from an end-user expression is + extracted. + + Dialogflow provides predefined system entities that + can match many common types of data. For example, + there are system entities for matching dates, times, + colors, email addresses, and so on. You can also + create your own custom entities for matching custom + data. For example, you could define a vegetable + entity that can match the types of vegetables + available for purchase with a grocery store agent. + + For more information, see the [Entity + guide](\ https://cloud.google.com/dialogflow/docs/entities-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, entity_type, language_code]) + if request is 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 = gcd_entity_type.CreateEntityTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entity_type is not None: + request.entity_type = entity_type + if language_code is not None: + request.language_code = language_code + + # 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_entity_type, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_entity_type(self, + request: Union[gcd_entity_type.UpdateEntityTypeRequest, dict] = None, + *, + entity_type: gcd_entity_type.EntityType = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_entity_type.EntityType: + r"""Updates the specified entity type. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.UpdateEntityTypeRequest, dict]): + The request object. The request message for + [EntityTypes.UpdateEntityType][google.cloud.dialogflow.v2.EntityTypes.UpdateEntityType]. + entity_type (:class:`google.cloud.dialogflow_v2.types.EntityType`): + Required. The entity type to update. + This corresponds to the ``entity_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (:class:`str`): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.EntityType: + Each intent parameter has a type, called the entity type, which dictates + exactly how data from an end-user expression is + extracted. + + Dialogflow provides predefined system entities that + can match many common types of data. For example, + there are system entities for matching dates, times, + colors, email addresses, and so on. You can also + create your own custom entities for matching custom + data. For example, you could define a vegetable + entity that can match the types of vegetables + available for purchase with a grocery store agent. + + For more information, see the [Entity + guide](\ https://cloud.google.com/dialogflow/docs/entities-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([entity_type, language_code]) + if request is 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 = gcd_entity_type.UpdateEntityTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if entity_type is not None: + request.entity_type = entity_type + if language_code is not None: + request.language_code = language_code + + # 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_entity_type, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("entity_type.name", request.entity_type.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_entity_type(self, + request: Union[entity_type.DeleteEntityTypeRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified entity type. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.DeleteEntityTypeRequest, dict]): + The request object. The request message for + [EntityTypes.DeleteEntityType][google.cloud.dialogflow.v2.EntityTypes.DeleteEntityType]. + name (:class:`str`): + Required. The name of the entity type to delete. Format: + ``projects//agent/entityTypes/``. + + 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 = entity_type.DeleteEntityTypeRequest(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_entity_type, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def batch_update_entity_types(self, + request: Union[entity_type.BatchUpdateEntityTypesRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates/Creates multiple entity types in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [BatchUpdateEntityTypesResponse][google.cloud.dialogflow.v2.BatchUpdateEntityTypesResponse] + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.BatchUpdateEntityTypesRequest, dict]): + The request object. The request message for + [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntityTypes]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.dialogflow_v2.types.BatchUpdateEntityTypesResponse` + The response message for + [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntityTypes]. + + """ + # Create or coerce a protobuf request object. + request = entity_type.BatchUpdateEntityTypesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_update_entity_types, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + entity_type.BatchUpdateEntityTypesResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def batch_delete_entity_types(self, + request: Union[entity_type.BatchDeleteEntityTypesRequest, dict] = None, + *, + parent: str = None, + entity_type_names: Sequence[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes entity types in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.BatchDeleteEntityTypesRequest, dict]): + The request object. The request message for + [EntityTypes.BatchDeleteEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchDeleteEntityTypes]. + parent (:class:`str`): + Required. The name of the agent to delete all entities + types for. Format: ``projects//agent``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entity_type_names (:class:`Sequence[str]`): + Required. The names entity types to delete. All names + must point to the same agent as ``parent``. + + This corresponds to the ``entity_type_names`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, entity_type_names]) + if request is 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 = entity_type.BatchDeleteEntityTypesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entity_type_names: + request.entity_type_names.extend(entity_type_names) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_delete_entity_types, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def batch_create_entities(self, + request: Union[entity_type.BatchCreateEntitiesRequest, dict] = None, + *, + parent: str = None, + entities: Sequence[entity_type.EntityType.Entity] = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates multiple new entities in the specified entity type. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.BatchCreateEntitiesRequest, dict]): + The request object. The request message for + [EntityTypes.BatchCreateEntities][google.cloud.dialogflow.v2.EntityTypes.BatchCreateEntities]. + parent (:class:`str`): + Required. The name of the entity type to create entities + in. Format: + ``projects//agent/entityTypes/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entities (:class:`Sequence[google.cloud.dialogflow_v2.types.EntityType.Entity]`): + Required. The entities to create. + This corresponds to the ``entities`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (:class:`str`): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, entities, language_code]) + if request is 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 = entity_type.BatchCreateEntitiesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if language_code is not None: + request.language_code = language_code + if entities: + request.entities.extend(entities) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_create_entities, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def batch_update_entities(self, + request: Union[entity_type.BatchUpdateEntitiesRequest, dict] = None, + *, + parent: str = None, + entities: Sequence[entity_type.EntityType.Entity] = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates or creates multiple entities in the specified entity + type. This method does not affect entities in the entity type + that aren't explicitly specified in the request. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.BatchUpdateEntitiesRequest, dict]): + The request object. The request message for + [EntityTypes.BatchUpdateEntities][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntities]. + parent (:class:`str`): + Required. The name of the entity type to update or + create entities in. Format: + ``projects//agent/entityTypes/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entities (:class:`Sequence[google.cloud.dialogflow_v2.types.EntityType.Entity]`): + Required. The entities to update or + create. + + This corresponds to the ``entities`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (:class:`str`): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, entities, language_code]) + if request is 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 = entity_type.BatchUpdateEntitiesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if language_code is not None: + request.language_code = language_code + if entities: + request.entities.extend(entities) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_update_entities, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def batch_delete_entities(self, + request: Union[entity_type.BatchDeleteEntitiesRequest, dict] = None, + *, + parent: str = None, + entity_values: Sequence[str] = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes entities in the specified entity type. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.BatchDeleteEntitiesRequest, dict]): + The request object. The request message for + [EntityTypes.BatchDeleteEntities][google.cloud.dialogflow.v2.EntityTypes.BatchDeleteEntities]. + parent (:class:`str`): + Required. The name of the entity type to delete entries + for. Format: + ``projects//agent/entityTypes/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entity_values (:class:`Sequence[str]`): + Required. The reference ``values`` of the entities to + delete. Note that these are not fully-qualified names, + i.e. they don't start with ``projects/``. + + This corresponds to the ``entity_values`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (:class:`str`): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, entity_values, language_code]) + if request is 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 = entity_type.BatchDeleteEntitiesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if language_code is not None: + request.language_code = language_code + if entity_values: + request.entity_values.extend(entity_values) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_delete_entities, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "EntityTypesAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/client.py new file mode 100644 index 000000000..9e5a844cb --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/client.py @@ -0,0 +1,1468 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.dialogflow_v2.services.entity_types import pagers +from google.cloud.dialogflow_v2.types import entity_type +from google.cloud.dialogflow_v2.types import entity_type as gcd_entity_type +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import EntityTypesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import EntityTypesGrpcTransport +from .transports.grpc_asyncio import EntityTypesGrpcAsyncIOTransport + + +class EntityTypesClientMeta(type): + """Metaclass for the EntityTypes 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[EntityTypesTransport]] + _transport_registry["grpc"] = EntityTypesGrpcTransport + _transport_registry["grpc_asyncio"] = EntityTypesGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[EntityTypesTransport]: + """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 EntityTypesClient(metaclass=EntityTypesClientMeta): + """Service for managing + [EntityTypes][google.cloud.dialogflow.v2.EntityType]. + """ + + @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 = "dialogflow.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: + EntityTypesClient: 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: + EntityTypesClient: 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) -> EntityTypesTransport: + """Returns the transport used by the client instance. + + Returns: + EntityTypesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def entity_type_path(project: str,entity_type: str,) -> str: + """Returns a fully-qualified entity_type string.""" + return "projects/{project}/agent/entityTypes/{entity_type}".format(project=project, entity_type=entity_type, ) + + @staticmethod + def parse_entity_type_path(path: str) -> Dict[str,str]: + """Parses a entity_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/entityTypes/(?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, EntityTypesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the entity types 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, EntityTypesTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, EntityTypesTransport): + # transport is a EntityTypesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_entity_types(self, + request: Union[entity_type.ListEntityTypesRequest, dict] = None, + *, + parent: str = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEntityTypesPager: + r"""Returns the list of all entity types in the specified + agent. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListEntityTypesRequest, dict]): + The request object. The request message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2.EntityTypes.ListEntityTypes]. + parent (str): + Required. The agent to list all entity types from. + Format: ``projects//agent``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.services.entity_types.pagers.ListEntityTypesPager: + The response message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2.EntityTypes.ListEntityTypes]. + + 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, language_code]) + if request is 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 entity_type.ListEntityTypesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, entity_type.ListEntityTypesRequest): + request = entity_type.ListEntityTypesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if language_code is not None: + request.language_code = language_code + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_entity_types] + + # Certain 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.ListEntityTypesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_entity_type(self, + request: Union[entity_type.GetEntityTypeRequest, dict] = None, + *, + name: str = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> entity_type.EntityType: + r"""Retrieves the specified entity type. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetEntityTypeRequest, dict]): + The request object. The request message for + [EntityTypes.GetEntityType][google.cloud.dialogflow.v2.EntityTypes.GetEntityType]. + name (str): + Required. The name of the entity type. Format: + ``projects//agent/entityTypes/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.EntityType: + Each intent parameter has a type, called the entity type, which dictates + exactly how data from an end-user expression is + extracted. + + Dialogflow provides predefined system entities that + can match many common types of data. For example, + there are system entities for matching dates, times, + colors, email addresses, and so on. You can also + create your own custom entities for matching custom + data. For example, you could define a vegetable + entity that can match the types of vegetables + available for purchase with a grocery store agent. + + For more information, see the [Entity + guide](\ https://cloud.google.com/dialogflow/docs/entities-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, language_code]) + if request is 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 entity_type.GetEntityTypeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, entity_type.GetEntityTypeRequest): + request = entity_type.GetEntityTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if language_code is not None: + request.language_code = language_code + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_entity_type] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_entity_type(self, + request: Union[gcd_entity_type.CreateEntityTypeRequest, dict] = None, + *, + parent: str = None, + entity_type: gcd_entity_type.EntityType = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_entity_type.EntityType: + r"""Creates an entity type in the specified agent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.CreateEntityTypeRequest, dict]): + The request object. The request message for + [EntityTypes.CreateEntityType][google.cloud.dialogflow.v2.EntityTypes.CreateEntityType]. + parent (str): + Required. The agent to create a entity type for. Format: + ``projects//agent``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entity_type (google.cloud.dialogflow_v2.types.EntityType): + Required. The entity type to create. + This corresponds to the ``entity_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.EntityType: + Each intent parameter has a type, called the entity type, which dictates + exactly how data from an end-user expression is + extracted. + + Dialogflow provides predefined system entities that + can match many common types of data. For example, + there are system entities for matching dates, times, + colors, email addresses, and so on. You can also + create your own custom entities for matching custom + data. For example, you could define a vegetable + entity that can match the types of vegetables + available for purchase with a grocery store agent. + + For more information, see the [Entity + guide](\ https://cloud.google.com/dialogflow/docs/entities-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, entity_type, language_code]) + if request is 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 gcd_entity_type.CreateEntityTypeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_entity_type.CreateEntityTypeRequest): + request = gcd_entity_type.CreateEntityTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entity_type is not None: + request.entity_type = entity_type + if language_code is not None: + request.language_code = language_code + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_entity_type] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_entity_type(self, + request: Union[gcd_entity_type.UpdateEntityTypeRequest, dict] = None, + *, + entity_type: gcd_entity_type.EntityType = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_entity_type.EntityType: + r"""Updates the specified entity type. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.UpdateEntityTypeRequest, dict]): + The request object. The request message for + [EntityTypes.UpdateEntityType][google.cloud.dialogflow.v2.EntityTypes.UpdateEntityType]. + entity_type (google.cloud.dialogflow_v2.types.EntityType): + Required. The entity type to update. + This corresponds to the ``entity_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.EntityType: + Each intent parameter has a type, called the entity type, which dictates + exactly how data from an end-user expression is + extracted. + + Dialogflow provides predefined system entities that + can match many common types of data. For example, + there are system entities for matching dates, times, + colors, email addresses, and so on. You can also + create your own custom entities for matching custom + data. For example, you could define a vegetable + entity that can match the types of vegetables + available for purchase with a grocery store agent. + + For more information, see the [Entity + guide](\ https://cloud.google.com/dialogflow/docs/entities-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([entity_type, language_code]) + if request is 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 gcd_entity_type.UpdateEntityTypeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_entity_type.UpdateEntityTypeRequest): + request = gcd_entity_type.UpdateEntityTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if entity_type is not None: + request.entity_type = entity_type + if language_code is not None: + request.language_code = language_code + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_entity_type] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("entity_type.name", request.entity_type.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_entity_type(self, + request: Union[entity_type.DeleteEntityTypeRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified entity type. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.DeleteEntityTypeRequest, dict]): + The request object. The request message for + [EntityTypes.DeleteEntityType][google.cloud.dialogflow.v2.EntityTypes.DeleteEntityType]. + name (str): + Required. The name of the entity type to delete. Format: + ``projects//agent/entityTypes/``. + + 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 entity_type.DeleteEntityTypeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, entity_type.DeleteEntityTypeRequest): + request = entity_type.DeleteEntityTypeRequest(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_entity_type] + + # Certain 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 batch_update_entity_types(self, + request: Union[entity_type.BatchUpdateEntityTypesRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates/Creates multiple entity types in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [BatchUpdateEntityTypesResponse][google.cloud.dialogflow.v2.BatchUpdateEntityTypesResponse] + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.BatchUpdateEntityTypesRequest, dict]): + The request object. The request message for + [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntityTypes]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.dialogflow_v2.types.BatchUpdateEntityTypesResponse` + The response message for + [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntityTypes]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a entity_type.BatchUpdateEntityTypesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, entity_type.BatchUpdateEntityTypesRequest): + request = entity_type.BatchUpdateEntityTypesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_update_entity_types] + + # Certain 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, + entity_type.BatchUpdateEntityTypesResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def batch_delete_entity_types(self, + request: Union[entity_type.BatchDeleteEntityTypesRequest, dict] = None, + *, + parent: str = None, + entity_type_names: Sequence[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes entity types in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.BatchDeleteEntityTypesRequest, dict]): + The request object. The request message for + [EntityTypes.BatchDeleteEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchDeleteEntityTypes]. + parent (str): + Required. The name of the agent to delete all entities + types for. Format: ``projects//agent``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entity_type_names (Sequence[str]): + Required. The names entity types to delete. All names + must point to the same agent as ``parent``. + + This corresponds to the ``entity_type_names`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, entity_type_names]) + if request is 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 entity_type.BatchDeleteEntityTypesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, entity_type.BatchDeleteEntityTypesRequest): + request = entity_type.BatchDeleteEntityTypesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entity_type_names is not None: + request.entity_type_names = entity_type_names + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_delete_entity_types] + + # Certain 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, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def batch_create_entities(self, + request: Union[entity_type.BatchCreateEntitiesRequest, dict] = None, + *, + parent: str = None, + entities: Sequence[entity_type.EntityType.Entity] = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates multiple new entities in the specified entity type. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.BatchCreateEntitiesRequest, dict]): + The request object. The request message for + [EntityTypes.BatchCreateEntities][google.cloud.dialogflow.v2.EntityTypes.BatchCreateEntities]. + parent (str): + Required. The name of the entity type to create entities + in. Format: + ``projects//agent/entityTypes/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entities (Sequence[google.cloud.dialogflow_v2.types.EntityType.Entity]): + Required. The entities to create. + This corresponds to the ``entities`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, entities, language_code]) + if request is 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 entity_type.BatchCreateEntitiesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, entity_type.BatchCreateEntitiesRequest): + request = entity_type.BatchCreateEntitiesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entities is not None: + request.entities = entities + if language_code is not None: + request.language_code = language_code + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_create_entities] + + # Certain 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, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def batch_update_entities(self, + request: Union[entity_type.BatchUpdateEntitiesRequest, dict] = None, + *, + parent: str = None, + entities: Sequence[entity_type.EntityType.Entity] = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates or creates multiple entities in the specified entity + type. This method does not affect entities in the entity type + that aren't explicitly specified in the request. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.BatchUpdateEntitiesRequest, dict]): + The request object. The request message for + [EntityTypes.BatchUpdateEntities][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntities]. + parent (str): + Required. The name of the entity type to update or + create entities in. Format: + ``projects//agent/entityTypes/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entities (Sequence[google.cloud.dialogflow_v2.types.EntityType.Entity]): + Required. The entities to update or + create. + + This corresponds to the ``entities`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, entities, language_code]) + if request is 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 entity_type.BatchUpdateEntitiesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, entity_type.BatchUpdateEntitiesRequest): + request = entity_type.BatchUpdateEntitiesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entities is not None: + request.entities = entities + if language_code is not None: + request.language_code = language_code + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_update_entities] + + # Certain 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, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def batch_delete_entities(self, + request: Union[entity_type.BatchDeleteEntitiesRequest, dict] = None, + *, + parent: str = None, + entity_values: Sequence[str] = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes entities in the specified entity type. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.BatchDeleteEntitiesRequest, dict]): + The request object. The request message for + [EntityTypes.BatchDeleteEntities][google.cloud.dialogflow.v2.EntityTypes.BatchDeleteEntities]. + parent (str): + Required. The name of the entity type to delete entries + for. Format: + ``projects//agent/entityTypes/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entity_values (Sequence[str]): + Required. The reference ``values`` of the entities to + delete. Note that these are not fully-qualified names, + i.e. they don't start with ``projects/``. + + This corresponds to the ``entity_values`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, entity_values, language_code]) + if request is 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 entity_type.BatchDeleteEntitiesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, entity_type.BatchDeleteEntitiesRequest): + request = entity_type.BatchDeleteEntitiesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entity_values is not None: + request.entity_values = entity_values + if language_code is not None: + request.language_code = language_code + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_delete_entities] + + # Certain 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, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "EntityTypesClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/pagers.py new file mode 100644 index 000000000..549355ea7 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflow_v2.types import entity_type + + +class ListEntityTypesPager: + """A pager for iterating through ``list_entity_types`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListEntityTypesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``entity_types`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEntityTypes`` requests and continue to iterate + through the ``entity_types`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListEntityTypesResponse` + 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[..., entity_type.ListEntityTypesResponse], + request: entity_type.ListEntityTypesRequest, + response: entity_type.ListEntityTypesResponse, + *, + 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.dialogflow_v2.types.ListEntityTypesRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListEntityTypesResponse): + 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 = entity_type.ListEntityTypesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[entity_type.ListEntityTypesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[entity_type.EntityType]: + for page in self.pages: + yield from page.entity_types + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEntityTypesAsyncPager: + """A pager for iterating through ``list_entity_types`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListEntityTypesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``entity_types`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEntityTypes`` requests and continue to iterate + through the ``entity_types`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListEntityTypesResponse` + 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[entity_type.ListEntityTypesResponse]], + request: entity_type.ListEntityTypesRequest, + response: entity_type.ListEntityTypesResponse, + *, + 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.dialogflow_v2.types.ListEntityTypesRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListEntityTypesResponse): + 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 = entity_type.ListEntityTypesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[entity_type.ListEntityTypesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[entity_type.EntityType]: + async def async_generator(): + async for page in self.pages: + for response in page.entity_types: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/__init__.py new file mode 100644 index 000000000..1a2aa82dc --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/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 EntityTypesTransport +from .grpc import EntityTypesGrpcTransport +from .grpc_asyncio import EntityTypesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[EntityTypesTransport]] +_transport_registry['grpc'] = EntityTypesGrpcTransport +_transport_registry['grpc_asyncio'] = EntityTypesGrpcAsyncIOTransport + +__all__ = ( + 'EntityTypesTransport', + 'EntityTypesGrpcTransport', + 'EntityTypesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/base.py new file mode 100644 index 000000000..106bf3ac5 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/base.py @@ -0,0 +1,282 @@ +# -*- 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.types import entity_type +from google.cloud.dialogflow_v2.types import entity_type as gcd_entity_type +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-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class EntityTypesTransport(abc.ABC): + """Abstract transport class for EntityTypes.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_entity_types: gapic_v1.method.wrap_method( + self.list_entity_types, + default_timeout=None, + client_info=client_info, + ), + self.get_entity_type: gapic_v1.method.wrap_method( + self.get_entity_type, + default_timeout=None, + client_info=client_info, + ), + self.create_entity_type: gapic_v1.method.wrap_method( + self.create_entity_type, + default_timeout=None, + client_info=client_info, + ), + self.update_entity_type: gapic_v1.method.wrap_method( + self.update_entity_type, + default_timeout=None, + client_info=client_info, + ), + self.delete_entity_type: gapic_v1.method.wrap_method( + self.delete_entity_type, + default_timeout=None, + client_info=client_info, + ), + self.batch_update_entity_types: gapic_v1.method.wrap_method( + self.batch_update_entity_types, + default_timeout=None, + client_info=client_info, + ), + self.batch_delete_entity_types: gapic_v1.method.wrap_method( + self.batch_delete_entity_types, + default_timeout=None, + client_info=client_info, + ), + self.batch_create_entities: gapic_v1.method.wrap_method( + self.batch_create_entities, + default_timeout=None, + client_info=client_info, + ), + self.batch_update_entities: gapic_v1.method.wrap_method( + self.batch_update_entities, + default_timeout=None, + client_info=client_info, + ), + self.batch_delete_entities: gapic_v1.method.wrap_method( + self.batch_delete_entities, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_entity_types(self) -> Callable[ + [entity_type.ListEntityTypesRequest], + Union[ + entity_type.ListEntityTypesResponse, + Awaitable[entity_type.ListEntityTypesResponse] + ]]: + raise NotImplementedError() + + @property + def get_entity_type(self) -> Callable[ + [entity_type.GetEntityTypeRequest], + Union[ + entity_type.EntityType, + Awaitable[entity_type.EntityType] + ]]: + raise NotImplementedError() + + @property + def create_entity_type(self) -> Callable[ + [gcd_entity_type.CreateEntityTypeRequest], + Union[ + gcd_entity_type.EntityType, + Awaitable[gcd_entity_type.EntityType] + ]]: + raise NotImplementedError() + + @property + def update_entity_type(self) -> Callable[ + [gcd_entity_type.UpdateEntityTypeRequest], + Union[ + gcd_entity_type.EntityType, + Awaitable[gcd_entity_type.EntityType] + ]]: + raise NotImplementedError() + + @property + def delete_entity_type(self) -> Callable[ + [entity_type.DeleteEntityTypeRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def batch_update_entity_types(self) -> Callable[ + [entity_type.BatchUpdateEntityTypesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def batch_delete_entity_types(self) -> Callable[ + [entity_type.BatchDeleteEntityTypesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def batch_create_entities(self) -> Callable[ + [entity_type.BatchCreateEntitiesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def batch_update_entities(self) -> Callable[ + [entity_type.BatchUpdateEntitiesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def batch_delete_entities(self) -> Callable[ + [entity_type.BatchDeleteEntitiesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'EntityTypesTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/grpc.py new file mode 100644 index 000000000..6b68f0144 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/grpc.py @@ -0,0 +1,595 @@ +# -*- 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 +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import entity_type +from google.cloud.dialogflow_v2.types import entity_type as gcd_entity_type +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import EntityTypesTransport, DEFAULT_CLIENT_INFO + + +class EntityTypesGrpcTransport(EntityTypesTransport): + """gRPC backend transport for EntityTypes. + + Service for managing + [EntityTypes][google.cloud.dialogflow.v2.EntityType]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 = 'dialogflow.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 list_entity_types(self) -> Callable[ + [entity_type.ListEntityTypesRequest], + entity_type.ListEntityTypesResponse]: + r"""Return a callable for the list entity types method over gRPC. + + Returns the list of all entity types in the specified + agent. + + Returns: + Callable[[~.ListEntityTypesRequest], + ~.ListEntityTypesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entity_types' not in self._stubs: + self._stubs['list_entity_types'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.EntityTypes/ListEntityTypes', + request_serializer=entity_type.ListEntityTypesRequest.serialize, + response_deserializer=entity_type.ListEntityTypesResponse.deserialize, + ) + return self._stubs['list_entity_types'] + + @property + def get_entity_type(self) -> Callable[ + [entity_type.GetEntityTypeRequest], + entity_type.EntityType]: + r"""Return a callable for the get entity type method over gRPC. + + Retrieves the specified entity type. + + Returns: + Callable[[~.GetEntityTypeRequest], + ~.EntityType]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entity_type' not in self._stubs: + self._stubs['get_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.EntityTypes/GetEntityType', + request_serializer=entity_type.GetEntityTypeRequest.serialize, + response_deserializer=entity_type.EntityType.deserialize, + ) + return self._stubs['get_entity_type'] + + @property + def create_entity_type(self) -> Callable[ + [gcd_entity_type.CreateEntityTypeRequest], + gcd_entity_type.EntityType]: + r"""Return a callable for the create entity type method over gRPC. + + Creates an entity type in the specified agent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.CreateEntityTypeRequest], + ~.EntityType]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entity_type' not in self._stubs: + self._stubs['create_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.EntityTypes/CreateEntityType', + request_serializer=gcd_entity_type.CreateEntityTypeRequest.serialize, + response_deserializer=gcd_entity_type.EntityType.deserialize, + ) + return self._stubs['create_entity_type'] + + @property + def update_entity_type(self) -> Callable[ + [gcd_entity_type.UpdateEntityTypeRequest], + gcd_entity_type.EntityType]: + r"""Return a callable for the update entity type method over gRPC. + + Updates the specified entity type. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.UpdateEntityTypeRequest], + ~.EntityType]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entity_type' not in self._stubs: + self._stubs['update_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.EntityTypes/UpdateEntityType', + request_serializer=gcd_entity_type.UpdateEntityTypeRequest.serialize, + response_deserializer=gcd_entity_type.EntityType.deserialize, + ) + return self._stubs['update_entity_type'] + + @property + def delete_entity_type(self) -> Callable[ + [entity_type.DeleteEntityTypeRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete entity type method over gRPC. + + Deletes the specified entity type. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.DeleteEntityTypeRequest], + ~.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_entity_type' not in self._stubs: + self._stubs['delete_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.EntityTypes/DeleteEntityType', + request_serializer=entity_type.DeleteEntityTypeRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_entity_type'] + + @property + def batch_update_entity_types(self) -> Callable[ + [entity_type.BatchUpdateEntityTypesRequest], + operations_pb2.Operation]: + r"""Return a callable for the batch update entity types method over gRPC. + + Updates/Creates multiple entity types in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [BatchUpdateEntityTypesResponse][google.cloud.dialogflow.v2.BatchUpdateEntityTypesResponse] + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.BatchUpdateEntityTypesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_update_entity_types' not in self._stubs: + self._stubs['batch_update_entity_types'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.EntityTypes/BatchUpdateEntityTypes', + request_serializer=entity_type.BatchUpdateEntityTypesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_update_entity_types'] + + @property + def batch_delete_entity_types(self) -> Callable[ + [entity_type.BatchDeleteEntityTypesRequest], + operations_pb2.Operation]: + r"""Return a callable for the batch delete entity types method over gRPC. + + Deletes entity types in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.BatchDeleteEntityTypesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_delete_entity_types' not in self._stubs: + self._stubs['batch_delete_entity_types'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.EntityTypes/BatchDeleteEntityTypes', + request_serializer=entity_type.BatchDeleteEntityTypesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_delete_entity_types'] + + @property + def batch_create_entities(self) -> Callable[ + [entity_type.BatchCreateEntitiesRequest], + operations_pb2.Operation]: + r"""Return a callable for the batch create entities method over gRPC. + + Creates multiple new entities in the specified entity type. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.BatchCreateEntitiesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_create_entities' not in self._stubs: + self._stubs['batch_create_entities'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.EntityTypes/BatchCreateEntities', + request_serializer=entity_type.BatchCreateEntitiesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_create_entities'] + + @property + def batch_update_entities(self) -> Callable[ + [entity_type.BatchUpdateEntitiesRequest], + operations_pb2.Operation]: + r"""Return a callable for the batch update entities method over gRPC. + + Updates or creates multiple entities in the specified entity + type. This method does not affect entities in the entity type + that aren't explicitly specified in the request. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.BatchUpdateEntitiesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_update_entities' not in self._stubs: + self._stubs['batch_update_entities'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.EntityTypes/BatchUpdateEntities', + request_serializer=entity_type.BatchUpdateEntitiesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_update_entities'] + + @property + def batch_delete_entities(self) -> Callable[ + [entity_type.BatchDeleteEntitiesRequest], + operations_pb2.Operation]: + r"""Return a callable for the batch delete entities method over gRPC. + + Deletes entities in the specified entity type. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.BatchDeleteEntitiesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_delete_entities' not in self._stubs: + self._stubs['batch_delete_entities'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.EntityTypes/BatchDeleteEntities', + request_serializer=entity_type.BatchDeleteEntitiesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_delete_entities'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'EntityTypesGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/grpc_asyncio.py new file mode 100644 index 000000000..58b25bb30 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/grpc_asyncio.py @@ -0,0 +1,599 @@ +# -*- 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 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import entity_type +from google.cloud.dialogflow_v2.types import entity_type as gcd_entity_type +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import EntityTypesTransport, DEFAULT_CLIENT_INFO +from .grpc import EntityTypesGrpcTransport + + +class EntityTypesGrpcAsyncIOTransport(EntityTypesTransport): + """gRPC AsyncIO backend transport for EntityTypes. + + Service for managing + [EntityTypes][google.cloud.dialogflow.v2.EntityType]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 list_entity_types(self) -> Callable[ + [entity_type.ListEntityTypesRequest], + Awaitable[entity_type.ListEntityTypesResponse]]: + r"""Return a callable for the list entity types method over gRPC. + + Returns the list of all entity types in the specified + agent. + + Returns: + Callable[[~.ListEntityTypesRequest], + Awaitable[~.ListEntityTypesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entity_types' not in self._stubs: + self._stubs['list_entity_types'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.EntityTypes/ListEntityTypes', + request_serializer=entity_type.ListEntityTypesRequest.serialize, + response_deserializer=entity_type.ListEntityTypesResponse.deserialize, + ) + return self._stubs['list_entity_types'] + + @property + def get_entity_type(self) -> Callable[ + [entity_type.GetEntityTypeRequest], + Awaitable[entity_type.EntityType]]: + r"""Return a callable for the get entity type method over gRPC. + + Retrieves the specified entity type. + + Returns: + Callable[[~.GetEntityTypeRequest], + Awaitable[~.EntityType]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entity_type' not in self._stubs: + self._stubs['get_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.EntityTypes/GetEntityType', + request_serializer=entity_type.GetEntityTypeRequest.serialize, + response_deserializer=entity_type.EntityType.deserialize, + ) + return self._stubs['get_entity_type'] + + @property + def create_entity_type(self) -> Callable[ + [gcd_entity_type.CreateEntityTypeRequest], + Awaitable[gcd_entity_type.EntityType]]: + r"""Return a callable for the create entity type method over gRPC. + + Creates an entity type in the specified agent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.CreateEntityTypeRequest], + Awaitable[~.EntityType]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entity_type' not in self._stubs: + self._stubs['create_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.EntityTypes/CreateEntityType', + request_serializer=gcd_entity_type.CreateEntityTypeRequest.serialize, + response_deserializer=gcd_entity_type.EntityType.deserialize, + ) + return self._stubs['create_entity_type'] + + @property + def update_entity_type(self) -> Callable[ + [gcd_entity_type.UpdateEntityTypeRequest], + Awaitable[gcd_entity_type.EntityType]]: + r"""Return a callable for the update entity type method over gRPC. + + Updates the specified entity type. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.UpdateEntityTypeRequest], + Awaitable[~.EntityType]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entity_type' not in self._stubs: + self._stubs['update_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.EntityTypes/UpdateEntityType', + request_serializer=gcd_entity_type.UpdateEntityTypeRequest.serialize, + response_deserializer=gcd_entity_type.EntityType.deserialize, + ) + return self._stubs['update_entity_type'] + + @property + def delete_entity_type(self) -> Callable[ + [entity_type.DeleteEntityTypeRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete entity type method over gRPC. + + Deletes the specified entity type. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.DeleteEntityTypeRequest], + 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_entity_type' not in self._stubs: + self._stubs['delete_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.EntityTypes/DeleteEntityType', + request_serializer=entity_type.DeleteEntityTypeRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_entity_type'] + + @property + def batch_update_entity_types(self) -> Callable[ + [entity_type.BatchUpdateEntityTypesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the batch update entity types method over gRPC. + + Updates/Creates multiple entity types in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [BatchUpdateEntityTypesResponse][google.cloud.dialogflow.v2.BatchUpdateEntityTypesResponse] + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.BatchUpdateEntityTypesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_update_entity_types' not in self._stubs: + self._stubs['batch_update_entity_types'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.EntityTypes/BatchUpdateEntityTypes', + request_serializer=entity_type.BatchUpdateEntityTypesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_update_entity_types'] + + @property + def batch_delete_entity_types(self) -> Callable[ + [entity_type.BatchDeleteEntityTypesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the batch delete entity types method over gRPC. + + Deletes entity types in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.BatchDeleteEntityTypesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_delete_entity_types' not in self._stubs: + self._stubs['batch_delete_entity_types'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.EntityTypes/BatchDeleteEntityTypes', + request_serializer=entity_type.BatchDeleteEntityTypesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_delete_entity_types'] + + @property + def batch_create_entities(self) -> Callable[ + [entity_type.BatchCreateEntitiesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the batch create entities method over gRPC. + + Creates multiple new entities in the specified entity type. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.BatchCreateEntitiesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_create_entities' not in self._stubs: + self._stubs['batch_create_entities'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.EntityTypes/BatchCreateEntities', + request_serializer=entity_type.BatchCreateEntitiesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_create_entities'] + + @property + def batch_update_entities(self) -> Callable[ + [entity_type.BatchUpdateEntitiesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the batch update entities method over gRPC. + + Updates or creates multiple entities in the specified entity + type. This method does not affect entities in the entity type + that aren't explicitly specified in the request. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.BatchUpdateEntitiesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_update_entities' not in self._stubs: + self._stubs['batch_update_entities'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.EntityTypes/BatchUpdateEntities', + request_serializer=entity_type.BatchUpdateEntitiesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_update_entities'] + + @property + def batch_delete_entities(self) -> Callable[ + [entity_type.BatchDeleteEntitiesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the batch delete entities method over gRPC. + + Deletes entities in the specified entity type. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.BatchDeleteEntitiesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_delete_entities' not in self._stubs: + self._stubs['batch_delete_entities'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.EntityTypes/BatchDeleteEntities', + request_serializer=entity_type.BatchDeleteEntitiesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_delete_entities'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'EntityTypesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/__init__.py new file mode 100644 index 000000000..a3ad29ecd --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/__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 EnvironmentsClient +from .async_client import EnvironmentsAsyncClient + +__all__ = ( + 'EnvironmentsClient', + 'EnvironmentsAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/async_client.py new file mode 100644 index 000000000..ab4bca33b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/async_client.py @@ -0,0 +1,617 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2.services.environments import pagers +from google.cloud.dialogflow_v2.types import environment +from google.cloud.dialogflow_v2.types import fulfillment +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport +from .client import EnvironmentsClient + + +class EnvironmentsAsyncClient: + """Service for managing + [Environments][google.cloud.dialogflow.v2.Environment]. + """ + + _client: EnvironmentsClient + + DEFAULT_ENDPOINT = EnvironmentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = EnvironmentsClient.DEFAULT_MTLS_ENDPOINT + + environment_path = staticmethod(EnvironmentsClient.environment_path) + parse_environment_path = staticmethod(EnvironmentsClient.parse_environment_path) + fulfillment_path = staticmethod(EnvironmentsClient.fulfillment_path) + parse_fulfillment_path = staticmethod(EnvironmentsClient.parse_fulfillment_path) + version_path = staticmethod(EnvironmentsClient.version_path) + parse_version_path = staticmethod(EnvironmentsClient.parse_version_path) + common_billing_account_path = staticmethod(EnvironmentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(EnvironmentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(EnvironmentsClient.common_folder_path) + parse_common_folder_path = staticmethod(EnvironmentsClient.parse_common_folder_path) + common_organization_path = staticmethod(EnvironmentsClient.common_organization_path) + parse_common_organization_path = staticmethod(EnvironmentsClient.parse_common_organization_path) + common_project_path = staticmethod(EnvironmentsClient.common_project_path) + parse_common_project_path = staticmethod(EnvironmentsClient.parse_common_project_path) + common_location_path = staticmethod(EnvironmentsClient.common_location_path) + parse_common_location_path = staticmethod(EnvironmentsClient.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: + EnvironmentsAsyncClient: The constructed client. + """ + return EnvironmentsClient.from_service_account_info.__func__(EnvironmentsAsyncClient, 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: + EnvironmentsAsyncClient: The constructed client. + """ + return EnvironmentsClient.from_service_account_file.__func__(EnvironmentsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> EnvironmentsTransport: + """Returns the transport used by the client instance. + + Returns: + EnvironmentsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(EnvironmentsClient).get_transport_class, type(EnvironmentsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, EnvironmentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the environments 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, ~.EnvironmentsTransport]): 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 = EnvironmentsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_environments(self, + request: Union[environment.ListEnvironmentsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEnvironmentsAsyncPager: + r"""Returns the list of all non-default environments of + the specified agent. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListEnvironmentsRequest, dict]): + The request object. The request message for + [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. + parent (:class:`str`): + Required. The agent to list all environments from. + Format: + + - ``projects//agent`` + - ``projects//locations//agent`` + + 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.dialogflow_v2.services.environments.pagers.ListEnvironmentsAsyncPager: + The response message for + [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. + + 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 = environment.ListEnvironmentsRequest(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_environments, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEnvironmentsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_environment(self, + request: Union[environment.GetEnvironmentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Retrieves the specified agent environment. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetEnvironmentRequest, dict]): + The request object. The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.v2.Environments.GetEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + request = environment.GetEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_environment(self, + request: Union[environment.CreateEnvironmentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Creates an agent environment. + + Args: + request (Union[google.cloud.dialogflow_v2.types.CreateEnvironmentRequest, dict]): + The request object. The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.v2.Environments.CreateEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + request = environment.CreateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_environment(self, + request: Union[environment.UpdateEnvironmentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment continues serving the previous + version of the agent. After the new agent version is done + loading, the environment is set back to the ``RUNNING`` state. + You can use "-" as Environment ID in environment name to update + an agent version in the default environment. WARNING: this will + negate all recent changes to the draft agent and can't be + undone. You may want to save the draft agent to a version before + calling this method. + + Args: + request (Union[google.cloud.dialogflow_v2.types.UpdateEnvironmentRequest, dict]): + The request object. The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.v2.Environments.UpdateEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + request = environment.UpdateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment.name", request.environment.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_environment(self, + request: Union[environment.DeleteEnvironmentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified agent environment. + + Args: + request (Union[google.cloud.dialogflow_v2.types.DeleteEnvironmentRequest, dict]): + The request object. The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.v2.Environments.DeleteEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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. + request = environment.DeleteEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_environment_history(self, + request: Union[environment.GetEnvironmentHistoryRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GetEnvironmentHistoryAsyncPager: + r"""Gets the history of the specified environment. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetEnvironmentHistoryRequest, dict]): + The request object. The request message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.services.environments.pagers.GetEnvironmentHistoryAsyncPager: + The response message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = environment.GetEnvironmentHistoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_environment_history, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.GetEnvironmentHistoryAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "EnvironmentsAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/client.py new file mode 100644 index 000000000..a4ec1fd64 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/client.py @@ -0,0 +1,838 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2.services.environments import pagers +from google.cloud.dialogflow_v2.types import environment +from google.cloud.dialogflow_v2.types import fulfillment +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import EnvironmentsGrpcTransport +from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport + + +class EnvironmentsClientMeta(type): + """Metaclass for the Environments 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[EnvironmentsTransport]] + _transport_registry["grpc"] = EnvironmentsGrpcTransport + _transport_registry["grpc_asyncio"] = EnvironmentsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[EnvironmentsTransport]: + """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 EnvironmentsClient(metaclass=EnvironmentsClientMeta): + """Service for managing + [Environments][google.cloud.dialogflow.v2.Environment]. + """ + + @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 = "dialogflow.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: + EnvironmentsClient: 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: + EnvironmentsClient: 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) -> EnvironmentsTransport: + """Returns the transport used by the client instance. + + Returns: + EnvironmentsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def environment_path(project: str,environment: str,) -> str: + """Returns a fully-qualified environment string.""" + return "projects/{project}/agent/environments/{environment}".format(project=project, environment=environment, ) + + @staticmethod + def parse_environment_path(path: str) -> Dict[str,str]: + """Parses a environment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/environments/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def fulfillment_path(project: str,) -> str: + """Returns a fully-qualified fulfillment string.""" + return "projects/{project}/agent/fulfillment".format(project=project, ) + + @staticmethod + def parse_fulfillment_path(path: str) -> Dict[str,str]: + """Parses a fulfillment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/fulfillment$", path) + return m.groupdict() if m else {} + + @staticmethod + def version_path(project: str,version: str,) -> str: + """Returns a fully-qualified version string.""" + return "projects/{project}/agent/versions/{version}".format(project=project, version=version, ) + + @staticmethod + def parse_version_path(path: str) -> Dict[str,str]: + """Parses a version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/versions/(?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, EnvironmentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the environments 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, EnvironmentsTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, EnvironmentsTransport): + # transport is a EnvironmentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_environments(self, + request: Union[environment.ListEnvironmentsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEnvironmentsPager: + r"""Returns the list of all non-default environments of + the specified agent. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListEnvironmentsRequest, dict]): + The request object. The request message for + [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. + parent (str): + Required. The agent to list all environments from. + Format: + + - ``projects//agent`` + - ``projects//locations//agent`` + + 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.dialogflow_v2.services.environments.pagers.ListEnvironmentsPager: + The response message for + [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. + + 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 environment.ListEnvironmentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.ListEnvironmentsRequest): + request = environment.ListEnvironmentsRequest(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_environments] + + # Certain 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.ListEnvironmentsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_environment(self, + request: Union[environment.GetEnvironmentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Retrieves the specified agent environment. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetEnvironmentRequest, dict]): + The request object. The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.v2.Environments.GetEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.GetEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.GetEnvironmentRequest): + request = environment.GetEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_environment(self, + request: Union[environment.CreateEnvironmentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Creates an agent environment. + + Args: + request (Union[google.cloud.dialogflow_v2.types.CreateEnvironmentRequest, dict]): + The request object. The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.v2.Environments.CreateEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.CreateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.CreateEnvironmentRequest): + request = environment.CreateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_environment(self, + request: Union[environment.UpdateEnvironmentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment continues serving the previous + version of the agent. After the new agent version is done + loading, the environment is set back to the ``RUNNING`` state. + You can use "-" as Environment ID in environment name to update + an agent version in the default environment. WARNING: this will + negate all recent changes to the draft agent and can't be + undone. You may want to save the draft agent to a version before + calling this method. + + Args: + request (Union[google.cloud.dialogflow_v2.types.UpdateEnvironmentRequest, dict]): + The request object. The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.v2.Environments.UpdateEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.UpdateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.UpdateEnvironmentRequest): + request = environment.UpdateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment.name", request.environment.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_environment(self, + request: Union[environment.DeleteEnvironmentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified agent environment. + + Args: + request (Union[google.cloud.dialogflow_v2.types.DeleteEnvironmentRequest, dict]): + The request object. The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.v2.Environments.DeleteEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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. + # Minor optimization to avoid making a copy if the user passes + # in a environment.DeleteEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.DeleteEnvironmentRequest): + request = environment.DeleteEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_environment] + + # Certain 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 get_environment_history(self, + request: Union[environment.GetEnvironmentHistoryRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GetEnvironmentHistoryPager: + r"""Gets the history of the specified environment. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetEnvironmentHistoryRequest, dict]): + The request object. The request message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.services.environments.pagers.GetEnvironmentHistoryPager: + The response message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.GetEnvironmentHistoryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.GetEnvironmentHistoryRequest): + request = environment.GetEnvironmentHistoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_environment_history] + + # Certain 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.GetEnvironmentHistoryPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "EnvironmentsClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/pagers.py new file mode 100644 index 000000000..ca86ef3d5 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/pagers.py @@ -0,0 +1,262 @@ +# -*- 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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflow_v2.types import environment + + +class ListEnvironmentsPager: + """A pager for iterating through ``list_environments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListEnvironmentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``environments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEnvironments`` requests and continue to iterate + through the ``environments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListEnvironmentsResponse` + 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[..., environment.ListEnvironmentsResponse], + request: environment.ListEnvironmentsRequest, + response: environment.ListEnvironmentsResponse, + *, + 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.dialogflow_v2.types.ListEnvironmentsRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListEnvironmentsResponse): + 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 = environment.ListEnvironmentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[environment.ListEnvironmentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[environment.Environment]: + for page in self.pages: + yield from page.environments + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEnvironmentsAsyncPager: + """A pager for iterating through ``list_environments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListEnvironmentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``environments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEnvironments`` requests and continue to iterate + through the ``environments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListEnvironmentsResponse` + 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[environment.ListEnvironmentsResponse]], + request: environment.ListEnvironmentsRequest, + response: environment.ListEnvironmentsResponse, + *, + 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.dialogflow_v2.types.ListEnvironmentsRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListEnvironmentsResponse): + 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 = environment.ListEnvironmentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[environment.ListEnvironmentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[environment.Environment]: + async def async_generator(): + async for page in self.pages: + for response in page.environments: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GetEnvironmentHistoryPager: + """A pager for iterating through ``get_environment_history`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.EnvironmentHistory` object, and + provides an ``__iter__`` method to iterate through its + ``entries`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GetEnvironmentHistory`` requests and continue to iterate + through the ``entries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.EnvironmentHistory` + 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[..., environment.EnvironmentHistory], + request: environment.GetEnvironmentHistoryRequest, + response: environment.EnvironmentHistory, + *, + 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.dialogflow_v2.types.GetEnvironmentHistoryRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.EnvironmentHistory): + 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 = environment.GetEnvironmentHistoryRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[environment.EnvironmentHistory]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[environment.EnvironmentHistory.Entry]: + for page in self.pages: + yield from page.entries + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GetEnvironmentHistoryAsyncPager: + """A pager for iterating through ``get_environment_history`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.EnvironmentHistory` object, and + provides an ``__aiter__`` method to iterate through its + ``entries`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GetEnvironmentHistory`` requests and continue to iterate + through the ``entries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.EnvironmentHistory` + 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[environment.EnvironmentHistory]], + request: environment.GetEnvironmentHistoryRequest, + response: environment.EnvironmentHistory, + *, + 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.dialogflow_v2.types.GetEnvironmentHistoryRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.EnvironmentHistory): + 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 = environment.GetEnvironmentHistoryRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[environment.EnvironmentHistory]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[environment.EnvironmentHistory.Entry]: + async def async_generator(): + async for page in self.pages: + for response in page.entries: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/__init__.py new file mode 100644 index 000000000..fac90efe0 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/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 EnvironmentsTransport +from .grpc import EnvironmentsGrpcTransport +from .grpc_asyncio import EnvironmentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[EnvironmentsTransport]] +_transport_registry['grpc'] = EnvironmentsGrpcTransport +_transport_registry['grpc_asyncio'] = EnvironmentsGrpcAsyncIOTransport + +__all__ = ( + 'EnvironmentsTransport', + 'EnvironmentsGrpcTransport', + 'EnvironmentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/base.py new file mode 100644 index 000000000..8f9171264 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.types import environment +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-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class EnvironmentsTransport(abc.ABC): + """Abstract transport class for Environments.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_environments: gapic_v1.method.wrap_method( + self.list_environments, + default_timeout=None, + client_info=client_info, + ), + self.get_environment: gapic_v1.method.wrap_method( + self.get_environment, + default_timeout=None, + client_info=client_info, + ), + self.create_environment: gapic_v1.method.wrap_method( + self.create_environment, + default_timeout=None, + client_info=client_info, + ), + self.update_environment: gapic_v1.method.wrap_method( + self.update_environment, + default_timeout=None, + client_info=client_info, + ), + self.delete_environment: gapic_v1.method.wrap_method( + self.delete_environment, + default_timeout=None, + client_info=client_info, + ), + self.get_environment_history: gapic_v1.method.wrap_method( + self.get_environment_history, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_environments(self) -> Callable[ + [environment.ListEnvironmentsRequest], + Union[ + environment.ListEnvironmentsResponse, + Awaitable[environment.ListEnvironmentsResponse] + ]]: + raise NotImplementedError() + + @property + def get_environment(self) -> Callable[ + [environment.GetEnvironmentRequest], + Union[ + environment.Environment, + Awaitable[environment.Environment] + ]]: + raise NotImplementedError() + + @property + def create_environment(self) -> Callable[ + [environment.CreateEnvironmentRequest], + Union[ + environment.Environment, + Awaitable[environment.Environment] + ]]: + raise NotImplementedError() + + @property + def update_environment(self) -> Callable[ + [environment.UpdateEnvironmentRequest], + Union[ + environment.Environment, + Awaitable[environment.Environment] + ]]: + raise NotImplementedError() + + @property + def delete_environment(self) -> Callable[ + [environment.DeleteEnvironmentRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_environment_history(self) -> Callable[ + [environment.GetEnvironmentHistoryRequest], + Union[ + environment.EnvironmentHistory, + Awaitable[environment.EnvironmentHistory] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'EnvironmentsTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/grpc.py new file mode 100644 index 000000000..40d909158 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/grpc.py @@ -0,0 +1,400 @@ +# -*- 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 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import environment +from google.protobuf import empty_pb2 # type: ignore +from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO + + +class EnvironmentsGrpcTransport(EnvironmentsTransport): + """gRPC backend transport for Environments. + + Service for managing + [Environments][google.cloud.dialogflow.v2.Environment]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 = 'dialogflow.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 list_environments(self) -> Callable[ + [environment.ListEnvironmentsRequest], + environment.ListEnvironmentsResponse]: + r"""Return a callable for the list environments method over gRPC. + + Returns the list of all non-default environments of + the specified agent. + + Returns: + Callable[[~.ListEnvironmentsRequest], + ~.ListEnvironmentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environments' not in self._stubs: + self._stubs['list_environments'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Environments/ListEnvironments', + request_serializer=environment.ListEnvironmentsRequest.serialize, + response_deserializer=environment.ListEnvironmentsResponse.deserialize, + ) + return self._stubs['list_environments'] + + @property + def get_environment(self) -> Callable[ + [environment.GetEnvironmentRequest], + environment.Environment]: + r"""Return a callable for the get environment method over gRPC. + + Retrieves the specified agent environment. + + Returns: + Callable[[~.GetEnvironmentRequest], + ~.Environment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environment' not in self._stubs: + self._stubs['get_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Environments/GetEnvironment', + request_serializer=environment.GetEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs['get_environment'] + + @property + def create_environment(self) -> Callable[ + [environment.CreateEnvironmentRequest], + environment.Environment]: + r"""Return a callable for the create environment method over gRPC. + + Creates an agent environment. + + Returns: + Callable[[~.CreateEnvironmentRequest], + ~.Environment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environment' not in self._stubs: + self._stubs['create_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Environments/CreateEnvironment', + request_serializer=environment.CreateEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs['create_environment'] + + @property + def update_environment(self) -> Callable[ + [environment.UpdateEnvironmentRequest], + environment.Environment]: + r"""Return a callable for the update environment method over gRPC. + + Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment continues serving the previous + version of the agent. After the new agent version is done + loading, the environment is set back to the ``RUNNING`` state. + You can use "-" as Environment ID in environment name to update + an agent version in the default environment. WARNING: this will + negate all recent changes to the draft agent and can't be + undone. You may want to save the draft agent to a version before + calling this method. + + Returns: + Callable[[~.UpdateEnvironmentRequest], + ~.Environment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environment' not in self._stubs: + self._stubs['update_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Environments/UpdateEnvironment', + request_serializer=environment.UpdateEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs['update_environment'] + + @property + def delete_environment(self) -> Callable[ + [environment.DeleteEnvironmentRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete environment method over gRPC. + + Deletes the specified agent environment. + + Returns: + Callable[[~.DeleteEnvironmentRequest], + ~.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_environment' not in self._stubs: + self._stubs['delete_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Environments/DeleteEnvironment', + request_serializer=environment.DeleteEnvironmentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_environment'] + + @property + def get_environment_history(self) -> Callable[ + [environment.GetEnvironmentHistoryRequest], + environment.EnvironmentHistory]: + r"""Return a callable for the get environment history method over gRPC. + + Gets the history of the specified environment. + + Returns: + Callable[[~.GetEnvironmentHistoryRequest], + ~.EnvironmentHistory]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environment_history' not in self._stubs: + self._stubs['get_environment_history'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Environments/GetEnvironmentHistory', + request_serializer=environment.GetEnvironmentHistoryRequest.serialize, + response_deserializer=environment.EnvironmentHistory.deserialize, + ) + return self._stubs['get_environment_history'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'EnvironmentsGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/grpc_asyncio.py new file mode 100644 index 000000000..470a94692 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/grpc_asyncio.py @@ -0,0 +1,404 @@ +# -*- 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 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import environment +from google.protobuf import empty_pb2 # type: ignore +from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO +from .grpc import EnvironmentsGrpcTransport + + +class EnvironmentsGrpcAsyncIOTransport(EnvironmentsTransport): + """gRPC AsyncIO backend transport for Environments. + + Service for managing + [Environments][google.cloud.dialogflow.v2.Environment]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 list_environments(self) -> Callable[ + [environment.ListEnvironmentsRequest], + Awaitable[environment.ListEnvironmentsResponse]]: + r"""Return a callable for the list environments method over gRPC. + + Returns the list of all non-default environments of + the specified agent. + + Returns: + Callable[[~.ListEnvironmentsRequest], + Awaitable[~.ListEnvironmentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environments' not in self._stubs: + self._stubs['list_environments'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Environments/ListEnvironments', + request_serializer=environment.ListEnvironmentsRequest.serialize, + response_deserializer=environment.ListEnvironmentsResponse.deserialize, + ) + return self._stubs['list_environments'] + + @property + def get_environment(self) -> Callable[ + [environment.GetEnvironmentRequest], + Awaitable[environment.Environment]]: + r"""Return a callable for the get environment method over gRPC. + + Retrieves the specified agent environment. + + Returns: + Callable[[~.GetEnvironmentRequest], + Awaitable[~.Environment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environment' not in self._stubs: + self._stubs['get_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Environments/GetEnvironment', + request_serializer=environment.GetEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs['get_environment'] + + @property + def create_environment(self) -> Callable[ + [environment.CreateEnvironmentRequest], + Awaitable[environment.Environment]]: + r"""Return a callable for the create environment method over gRPC. + + Creates an agent environment. + + Returns: + Callable[[~.CreateEnvironmentRequest], + Awaitable[~.Environment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environment' not in self._stubs: + self._stubs['create_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Environments/CreateEnvironment', + request_serializer=environment.CreateEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs['create_environment'] + + @property + def update_environment(self) -> Callable[ + [environment.UpdateEnvironmentRequest], + Awaitable[environment.Environment]]: + r"""Return a callable for the update environment method over gRPC. + + Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment continues serving the previous + version of the agent. After the new agent version is done + loading, the environment is set back to the ``RUNNING`` state. + You can use "-" as Environment ID in environment name to update + an agent version in the default environment. WARNING: this will + negate all recent changes to the draft agent and can't be + undone. You may want to save the draft agent to a version before + calling this method. + + Returns: + Callable[[~.UpdateEnvironmentRequest], + Awaitable[~.Environment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environment' not in self._stubs: + self._stubs['update_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Environments/UpdateEnvironment', + request_serializer=environment.UpdateEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs['update_environment'] + + @property + def delete_environment(self) -> Callable[ + [environment.DeleteEnvironmentRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete environment method over gRPC. + + Deletes the specified agent environment. + + Returns: + Callable[[~.DeleteEnvironmentRequest], + 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_environment' not in self._stubs: + self._stubs['delete_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Environments/DeleteEnvironment', + request_serializer=environment.DeleteEnvironmentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_environment'] + + @property + def get_environment_history(self) -> Callable[ + [environment.GetEnvironmentHistoryRequest], + Awaitable[environment.EnvironmentHistory]]: + r"""Return a callable for the get environment history method over gRPC. + + Gets the history of the specified environment. + + Returns: + Callable[[~.GetEnvironmentHistoryRequest], + Awaitable[~.EnvironmentHistory]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environment_history' not in self._stubs: + self._stubs['get_environment_history'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Environments/GetEnvironmentHistory', + request_serializer=environment.GetEnvironmentHistoryRequest.serialize, + response_deserializer=environment.EnvironmentHistory.deserialize, + ) + return self._stubs['get_environment_history'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'EnvironmentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/__init__.py new file mode 100644 index 000000000..95fd359ef --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/__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 FulfillmentsClient +from .async_client import FulfillmentsAsyncClient + +__all__ = ( + 'FulfillmentsClient', + 'FulfillmentsAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/async_client.py new file mode 100644 index 000000000..4ee67b17b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/async_client.py @@ -0,0 +1,352 @@ +# -*- 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 + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2.types import fulfillment +from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import FulfillmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import FulfillmentsGrpcAsyncIOTransport +from .client import FulfillmentsClient + + +class FulfillmentsAsyncClient: + """Service for managing + [Fulfillments][google.cloud.dialogflow.v2.Fulfillment]. + """ + + _client: FulfillmentsClient + + DEFAULT_ENDPOINT = FulfillmentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = FulfillmentsClient.DEFAULT_MTLS_ENDPOINT + + fulfillment_path = staticmethod(FulfillmentsClient.fulfillment_path) + parse_fulfillment_path = staticmethod(FulfillmentsClient.parse_fulfillment_path) + common_billing_account_path = staticmethod(FulfillmentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(FulfillmentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(FulfillmentsClient.common_folder_path) + parse_common_folder_path = staticmethod(FulfillmentsClient.parse_common_folder_path) + common_organization_path = staticmethod(FulfillmentsClient.common_organization_path) + parse_common_organization_path = staticmethod(FulfillmentsClient.parse_common_organization_path) + common_project_path = staticmethod(FulfillmentsClient.common_project_path) + parse_common_project_path = staticmethod(FulfillmentsClient.parse_common_project_path) + common_location_path = staticmethod(FulfillmentsClient.common_location_path) + parse_common_location_path = staticmethod(FulfillmentsClient.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: + FulfillmentsAsyncClient: The constructed client. + """ + return FulfillmentsClient.from_service_account_info.__func__(FulfillmentsAsyncClient, 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: + FulfillmentsAsyncClient: The constructed client. + """ + return FulfillmentsClient.from_service_account_file.__func__(FulfillmentsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> FulfillmentsTransport: + """Returns the transport used by the client instance. + + Returns: + FulfillmentsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(FulfillmentsClient).get_transport_class, type(FulfillmentsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, FulfillmentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the fulfillments 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, ~.FulfillmentsTransport]): 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 = FulfillmentsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_fulfillment(self, + request: Union[fulfillment.GetFulfillmentRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> fulfillment.Fulfillment: + r"""Retrieves the fulfillment. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetFulfillmentRequest, dict]): + The request object. The request message for + [Fulfillments.GetFulfillment][google.cloud.dialogflow.v2.Fulfillments.GetFulfillment]. + name (:class:`str`): + Required. The name of the fulfillment. Format: + ``projects//agent/fulfillment``. + + 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.dialogflow_v2.types.Fulfillment: + By default, your agent responds to a matched intent with a static response. + As an alternative, you can provide a more dynamic + response by using fulfillment. When you enable + fulfillment for an intent, Dialogflow responds to + that intent by calling a service that you define. For + example, if an end-user wants to schedule a haircut + on Friday, your service can check your database and + respond to the end-user with availability information + for Friday. + + For more information, see the [fulfillment + guide](\ https://cloud.google.com/dialogflow/docs/fulfillment-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = fulfillment.GetFulfillmentRequest(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_fulfillment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_fulfillment(self, + request: Union[gcd_fulfillment.UpdateFulfillmentRequest, dict] = None, + *, + fulfillment: gcd_fulfillment.Fulfillment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_fulfillment.Fulfillment: + r"""Updates the fulfillment. + + Args: + request (Union[google.cloud.dialogflow_v2.types.UpdateFulfillmentRequest, dict]): + The request object. The request message for + [Fulfillments.UpdateFulfillment][google.cloud.dialogflow.v2.Fulfillments.UpdateFulfillment]. + fulfillment (:class:`google.cloud.dialogflow_v2.types.Fulfillment`): + Required. The fulfillment to update. + This corresponds to the ``fulfillment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The mask to control which + fields get updated. If the mask is not + present, all fields will be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Fulfillment: + By default, your agent responds to a matched intent with a static response. + As an alternative, you can provide a more dynamic + response by using fulfillment. When you enable + fulfillment for an intent, Dialogflow responds to + that intent by calling a service that you define. For + example, if an end-user wants to schedule a haircut + on Friday, your service can check your database and + respond to the end-user with availability information + for Friday. + + For more information, see the [fulfillment + guide](\ https://cloud.google.com/dialogflow/docs/fulfillment-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([fulfillment, 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 = gcd_fulfillment.UpdateFulfillmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if fulfillment is not None: + request.fulfillment = fulfillment + 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_fulfillment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("fulfillment.name", request.fulfillment.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "FulfillmentsAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/client.py new file mode 100644 index 000000000..0703a58b1 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/client.py @@ -0,0 +1,550 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2.types import fulfillment +from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import FulfillmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import FulfillmentsGrpcTransport +from .transports.grpc_asyncio import FulfillmentsGrpcAsyncIOTransport + + +class FulfillmentsClientMeta(type): + """Metaclass for the Fulfillments 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[FulfillmentsTransport]] + _transport_registry["grpc"] = FulfillmentsGrpcTransport + _transport_registry["grpc_asyncio"] = FulfillmentsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[FulfillmentsTransport]: + """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 FulfillmentsClient(metaclass=FulfillmentsClientMeta): + """Service for managing + [Fulfillments][google.cloud.dialogflow.v2.Fulfillment]. + """ + + @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 = "dialogflow.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: + FulfillmentsClient: 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: + FulfillmentsClient: 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) -> FulfillmentsTransport: + """Returns the transport used by the client instance. + + Returns: + FulfillmentsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def fulfillment_path(project: str,) -> str: + """Returns a fully-qualified fulfillment string.""" + return "projects/{project}/agent/fulfillment".format(project=project, ) + + @staticmethod + def parse_fulfillment_path(path: str) -> Dict[str,str]: + """Parses a fulfillment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/fulfillment$", 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, FulfillmentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the fulfillments 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, FulfillmentsTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, FulfillmentsTransport): + # transport is a FulfillmentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def get_fulfillment(self, + request: Union[fulfillment.GetFulfillmentRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> fulfillment.Fulfillment: + r"""Retrieves the fulfillment. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetFulfillmentRequest, dict]): + The request object. The request message for + [Fulfillments.GetFulfillment][google.cloud.dialogflow.v2.Fulfillments.GetFulfillment]. + name (str): + Required. The name of the fulfillment. Format: + ``projects//agent/fulfillment``. + + 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.dialogflow_v2.types.Fulfillment: + By default, your agent responds to a matched intent with a static response. + As an alternative, you can provide a more dynamic + response by using fulfillment. When you enable + fulfillment for an intent, Dialogflow responds to + that intent by calling a service that you define. For + example, if an end-user wants to schedule a haircut + on Friday, your service can check your database and + respond to the end-user with availability information + for Friday. + + For more information, see the [fulfillment + guide](\ https://cloud.google.com/dialogflow/docs/fulfillment-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a fulfillment.GetFulfillmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, fulfillment.GetFulfillmentRequest): + request = fulfillment.GetFulfillmentRequest(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_fulfillment] + + # Certain 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 update_fulfillment(self, + request: Union[gcd_fulfillment.UpdateFulfillmentRequest, dict] = None, + *, + fulfillment: gcd_fulfillment.Fulfillment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_fulfillment.Fulfillment: + r"""Updates the fulfillment. + + Args: + request (Union[google.cloud.dialogflow_v2.types.UpdateFulfillmentRequest, dict]): + The request object. The request message for + [Fulfillments.UpdateFulfillment][google.cloud.dialogflow.v2.Fulfillments.UpdateFulfillment]. + fulfillment (google.cloud.dialogflow_v2.types.Fulfillment): + Required. The fulfillment to update. + This corresponds to the ``fulfillment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which + fields get updated. If the mask is not + present, all fields will be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Fulfillment: + By default, your agent responds to a matched intent with a static response. + As an alternative, you can provide a more dynamic + response by using fulfillment. When you enable + fulfillment for an intent, Dialogflow responds to + that intent by calling a service that you define. For + example, if an end-user wants to schedule a haircut + on Friday, your service can check your database and + respond to the end-user with availability information + for Friday. + + For more information, see the [fulfillment + guide](\ https://cloud.google.com/dialogflow/docs/fulfillment-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([fulfillment, 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 gcd_fulfillment.UpdateFulfillmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_fulfillment.UpdateFulfillmentRequest): + request = gcd_fulfillment.UpdateFulfillmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if fulfillment is not None: + request.fulfillment = fulfillment + 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_fulfillment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("fulfillment.name", request.fulfillment.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "FulfillmentsClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/__init__.py new file mode 100644 index 000000000..4b41f9212 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/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 FulfillmentsTransport +from .grpc import FulfillmentsGrpcTransport +from .grpc_asyncio import FulfillmentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[FulfillmentsTransport]] +_transport_registry['grpc'] = FulfillmentsGrpcTransport +_transport_registry['grpc_asyncio'] = FulfillmentsGrpcAsyncIOTransport + +__all__ = ( + 'FulfillmentsTransport', + 'FulfillmentsGrpcTransport', + 'FulfillmentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/base.py new file mode 100644 index 000000000..89eaf11cc --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/base.py @@ -0,0 +1,162 @@ +# -*- 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.types import fulfillment +from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class FulfillmentsTransport(abc.ABC): + """Abstract transport class for Fulfillments.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_fulfillment: gapic_v1.method.wrap_method( + self.get_fulfillment, + default_timeout=None, + client_info=client_info, + ), + self.update_fulfillment: gapic_v1.method.wrap_method( + self.update_fulfillment, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def get_fulfillment(self) -> Callable[ + [fulfillment.GetFulfillmentRequest], + Union[ + fulfillment.Fulfillment, + Awaitable[fulfillment.Fulfillment] + ]]: + raise NotImplementedError() + + @property + def update_fulfillment(self) -> Callable[ + [gcd_fulfillment.UpdateFulfillmentRequest], + Union[ + gcd_fulfillment.Fulfillment, + Awaitable[gcd_fulfillment.Fulfillment] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'FulfillmentsTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc.py new file mode 100644 index 000000000..b965b79e6 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc.py @@ -0,0 +1,282 @@ +# -*- 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 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import fulfillment +from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment +from .base import FulfillmentsTransport, DEFAULT_CLIENT_INFO + + +class FulfillmentsGrpcTransport(FulfillmentsTransport): + """gRPC backend transport for Fulfillments. + + Service for managing + [Fulfillments][google.cloud.dialogflow.v2.Fulfillment]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def get_fulfillment(self) -> Callable[ + [fulfillment.GetFulfillmentRequest], + fulfillment.Fulfillment]: + r"""Return a callable for the get fulfillment method over gRPC. + + Retrieves the fulfillment. + + Returns: + Callable[[~.GetFulfillmentRequest], + ~.Fulfillment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_fulfillment' not in self._stubs: + self._stubs['get_fulfillment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Fulfillments/GetFulfillment', + request_serializer=fulfillment.GetFulfillmentRequest.serialize, + response_deserializer=fulfillment.Fulfillment.deserialize, + ) + return self._stubs['get_fulfillment'] + + @property + def update_fulfillment(self) -> Callable[ + [gcd_fulfillment.UpdateFulfillmentRequest], + gcd_fulfillment.Fulfillment]: + r"""Return a callable for the update fulfillment method over gRPC. + + Updates the fulfillment. + + Returns: + Callable[[~.UpdateFulfillmentRequest], + ~.Fulfillment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_fulfillment' not in self._stubs: + self._stubs['update_fulfillment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Fulfillments/UpdateFulfillment', + request_serializer=gcd_fulfillment.UpdateFulfillmentRequest.serialize, + response_deserializer=gcd_fulfillment.Fulfillment.deserialize, + ) + return self._stubs['update_fulfillment'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'FulfillmentsGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc_asyncio.py new file mode 100644 index 000000000..08d3e7fb8 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc_asyncio.py @@ -0,0 +1,286 @@ +# -*- 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 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import fulfillment +from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment +from .base import FulfillmentsTransport, DEFAULT_CLIENT_INFO +from .grpc import FulfillmentsGrpcTransport + + +class FulfillmentsGrpcAsyncIOTransport(FulfillmentsTransport): + """gRPC AsyncIO backend transport for Fulfillments. + + Service for managing + [Fulfillments][google.cloud.dialogflow.v2.Fulfillment]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def get_fulfillment(self) -> Callable[ + [fulfillment.GetFulfillmentRequest], + Awaitable[fulfillment.Fulfillment]]: + r"""Return a callable for the get fulfillment method over gRPC. + + Retrieves the fulfillment. + + Returns: + Callable[[~.GetFulfillmentRequest], + Awaitable[~.Fulfillment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_fulfillment' not in self._stubs: + self._stubs['get_fulfillment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Fulfillments/GetFulfillment', + request_serializer=fulfillment.GetFulfillmentRequest.serialize, + response_deserializer=fulfillment.Fulfillment.deserialize, + ) + return self._stubs['get_fulfillment'] + + @property + def update_fulfillment(self) -> Callable[ + [gcd_fulfillment.UpdateFulfillmentRequest], + Awaitable[gcd_fulfillment.Fulfillment]]: + r"""Return a callable for the update fulfillment method over gRPC. + + Updates the fulfillment. + + Returns: + Callable[[~.UpdateFulfillmentRequest], + Awaitable[~.Fulfillment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_fulfillment' not in self._stubs: + self._stubs['update_fulfillment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Fulfillments/UpdateFulfillment', + request_serializer=gcd_fulfillment.UpdateFulfillmentRequest.serialize, + response_deserializer=gcd_fulfillment.Fulfillment.deserialize, + ) + return self._stubs['update_fulfillment'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'FulfillmentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/__init__.py new file mode 100644 index 000000000..8204500fb --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/__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 IntentsClient +from .async_client import IntentsAsyncClient + +__all__ = ( + 'IntentsClient', + 'IntentsAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/async_client.py new file mode 100644 index 000000000..e789f6207 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/async_client.py @@ -0,0 +1,921 @@ +# -*- 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 + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.dialogflow_v2.services.intents import pagers +from google.cloud.dialogflow_v2.types import context +from google.cloud.dialogflow_v2.types import intent +from google.cloud.dialogflow_v2.types import intent as gcd_intent +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import IntentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import IntentsGrpcAsyncIOTransport +from .client import IntentsClient + + +class IntentsAsyncClient: + """Service for managing [Intents][google.cloud.dialogflow.v2.Intent].""" + + _client: IntentsClient + + DEFAULT_ENDPOINT = IntentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = IntentsClient.DEFAULT_MTLS_ENDPOINT + + context_path = staticmethod(IntentsClient.context_path) + parse_context_path = staticmethod(IntentsClient.parse_context_path) + intent_path = staticmethod(IntentsClient.intent_path) + parse_intent_path = staticmethod(IntentsClient.parse_intent_path) + common_billing_account_path = staticmethod(IntentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(IntentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(IntentsClient.common_folder_path) + parse_common_folder_path = staticmethod(IntentsClient.parse_common_folder_path) + common_organization_path = staticmethod(IntentsClient.common_organization_path) + parse_common_organization_path = staticmethod(IntentsClient.parse_common_organization_path) + common_project_path = staticmethod(IntentsClient.common_project_path) + parse_common_project_path = staticmethod(IntentsClient.parse_common_project_path) + common_location_path = staticmethod(IntentsClient.common_location_path) + parse_common_location_path = staticmethod(IntentsClient.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: + IntentsAsyncClient: The constructed client. + """ + return IntentsClient.from_service_account_info.__func__(IntentsAsyncClient, 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: + IntentsAsyncClient: The constructed client. + """ + return IntentsClient.from_service_account_file.__func__(IntentsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> IntentsTransport: + """Returns the transport used by the client instance. + + Returns: + IntentsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(IntentsClient).get_transport_class, type(IntentsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, IntentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the intents 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, ~.IntentsTransport]): 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 = IntentsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_intents(self, + request: Union[intent.ListIntentsRequest, dict] = None, + *, + parent: str = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListIntentsAsyncPager: + r"""Returns the list of all intents in the specified + agent. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListIntentsRequest, dict]): + The request object. The request message for + [Intents.ListIntents][google.cloud.dialogflow.v2.Intents.ListIntents]. + parent (:class:`str`): + Required. The agent to list all intents from. Format: + ``projects//agent`` or + ``projects//locations//agent``. + + Alternatively, you can specify the environment to list + intents for. Format: + ``projects//agent/environments/`` + or + ``projects//locations//agent/environments/``. + Note: training phrases of the intents will not be + returned for non-draft environment. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (:class:`str`): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.services.intents.pagers.ListIntentsAsyncPager: + The response message for + [Intents.ListIntents][google.cloud.dialogflow.v2.Intents.ListIntents]. + + 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, language_code]) + if request is 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 = intent.ListIntentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if language_code is not None: + request.language_code = language_code + + # 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_intents, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListIntentsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_intent(self, + request: Union[intent.GetIntentRequest, dict] = None, + *, + name: str = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> intent.Intent: + r"""Retrieves the specified intent. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetIntentRequest, dict]): + The request object. The request message for + [Intents.GetIntent][google.cloud.dialogflow.v2.Intents.GetIntent]. + name (:class:`str`): + Required. The name of the intent. Format: + ``projects//agent/intents/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (:class:`str`): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Intent: + An intent categorizes an end-user's intention for one conversation turn. For + each agent, you define many intents, where your + combined intents can handle a complete conversation. + When an end-user writes or says something, referred + to as an end-user expression or end-user input, + Dialogflow matches the end-user input to the best + intent in your agent. Matching an intent is also + known as intent classification. + + For more information, see the [intent + guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, language_code]) + if request is 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 = intent.GetIntentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if language_code is not None: + request.language_code = language_code + + # 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_intent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_intent(self, + request: Union[gcd_intent.CreateIntentRequest, dict] = None, + *, + parent: str = None, + intent: gcd_intent.Intent = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_intent.Intent: + r"""Creates an intent in the specified agent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.CreateIntentRequest, dict]): + The request object. The request message for + [Intents.CreateIntent][google.cloud.dialogflow.v2.Intents.CreateIntent]. + parent (:class:`str`): + Required. The agent to create a intent for. Format: + ``projects//agent``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + intent (:class:`google.cloud.dialogflow_v2.types.Intent`): + Required. The intent to create. + This corresponds to the ``intent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (:class:`str`): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Intent: + An intent categorizes an end-user's intention for one conversation turn. For + each agent, you define many intents, where your + combined intents can handle a complete conversation. + When an end-user writes or says something, referred + to as an end-user expression or end-user input, + Dialogflow matches the end-user input to the best + intent in your agent. Matching an intent is also + known as intent classification. + + For more information, see the [intent + guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, intent, language_code]) + if request is 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 = gcd_intent.CreateIntentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if intent is not None: + request.intent = intent + if language_code is not None: + request.language_code = language_code + + # 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_intent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_intent(self, + request: Union[gcd_intent.UpdateIntentRequest, dict] = None, + *, + intent: gcd_intent.Intent = None, + language_code: str = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_intent.Intent: + r"""Updates the specified intent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.UpdateIntentRequest, dict]): + The request object. The request message for + [Intents.UpdateIntent][google.cloud.dialogflow.v2.Intents.UpdateIntent]. + intent (:class:`google.cloud.dialogflow_v2.types.Intent`): + Required. The intent to update. + This corresponds to the ``intent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (:class:`str`): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Intent: + An intent categorizes an end-user's intention for one conversation turn. For + each agent, you define many intents, where your + combined intents can handle a complete conversation. + When an end-user writes or says something, referred + to as an end-user expression or end-user input, + Dialogflow matches the end-user input to the best + intent in your agent. Matching an intent is also + known as intent classification. + + For more information, see the [intent + guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([intent, language_code, 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 = gcd_intent.UpdateIntentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if intent is not None: + request.intent = intent + if language_code is not None: + request.language_code = language_code + 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_intent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("intent.name", request.intent.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_intent(self, + request: Union[intent.DeleteIntentRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified intent and its direct or indirect followup + intents. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.DeleteIntentRequest, dict]): + The request object. The request message for + [Intents.DeleteIntent][google.cloud.dialogflow.v2.Intents.DeleteIntent]. + name (:class:`str`): + Required. The name of the intent to delete. If this + intent has direct or indirect followup intents, we also + delete them. Format: + ``projects//agent/intents/``. + + 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 = intent.DeleteIntentRequest(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_intent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def batch_update_intents(self, + request: Union[intent.BatchUpdateIntentsRequest, dict] = None, + *, + parent: str = None, + intent_batch_uri: str = None, + intent_batch_inline: intent.IntentBatch = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates/Creates multiple intents in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [BatchUpdateIntentsResponse][google.cloud.dialogflow.v2.BatchUpdateIntentsResponse] + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.BatchUpdateIntentsRequest, dict]): + The request object. + parent (:class:`str`): + Required. The name of the agent to update or create + intents in. Format: ``projects//agent``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + intent_batch_uri (:class:`str`): + The URI to a Google Cloud Storage + file containing intents to update or + create. The file format can either be a + serialized proto (of IntentBatch type) + or JSON object. Note: The URI must start + with "gs://". + + This corresponds to the ``intent_batch_uri`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + intent_batch_inline (:class:`google.cloud.dialogflow_v2.types.IntentBatch`): + The collection of intents to update + or create. + + This corresponds to the ``intent_batch_inline`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.dialogflow_v2.types.BatchUpdateIntentsResponse` + The response message for + [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2.Intents.BatchUpdateIntents]. + + """ + # 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, intent_batch_uri, intent_batch_inline]) + if request is 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 = intent.BatchUpdateIntentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if intent_batch_uri is not None: + request.intent_batch_uri = intent_batch_uri + if intent_batch_inline is not None: + request.intent_batch_inline = intent_batch_inline + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_update_intents, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + intent.BatchUpdateIntentsResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def batch_delete_intents(self, + request: Union[intent.BatchDeleteIntentsRequest, dict] = None, + *, + parent: str = None, + intents: Sequence[intent.Intent] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes intents in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.BatchDeleteIntentsRequest, dict]): + The request object. The request message for + [Intents.BatchDeleteIntents][google.cloud.dialogflow.v2.Intents.BatchDeleteIntents]. + parent (:class:`str`): + Required. The name of the agent to delete all entities + types for. Format: ``projects//agent``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + intents (:class:`Sequence[google.cloud.dialogflow_v2.types.Intent]`): + Required. The collection of intents to delete. Only + intent ``name`` must be filled in. + + This corresponds to the ``intents`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, intents]) + if request is 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 = intent.BatchDeleteIntentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if intents: + request.intents.extend(intents) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_delete_intents, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "IntentsAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/client.py new file mode 100644 index 000000000..b390e3d9c --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/client.py @@ -0,0 +1,1128 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.dialogflow_v2.services.intents import pagers +from google.cloud.dialogflow_v2.types import context +from google.cloud.dialogflow_v2.types import intent +from google.cloud.dialogflow_v2.types import intent as gcd_intent +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import IntentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import IntentsGrpcTransport +from .transports.grpc_asyncio import IntentsGrpcAsyncIOTransport + + +class IntentsClientMeta(type): + """Metaclass for the Intents 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[IntentsTransport]] + _transport_registry["grpc"] = IntentsGrpcTransport + _transport_registry["grpc_asyncio"] = IntentsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[IntentsTransport]: + """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 IntentsClient(metaclass=IntentsClientMeta): + """Service for managing [Intents][google.cloud.dialogflow.v2.Intent].""" + + @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 = "dialogflow.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: + IntentsClient: 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: + IntentsClient: 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) -> IntentsTransport: + """Returns the transport used by the client instance. + + Returns: + IntentsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def context_path(project: str,session: str,context: str,) -> str: + """Returns a fully-qualified context string.""" + return "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) + + @staticmethod + def parse_context_path(path: str) -> Dict[str,str]: + """Parses a context path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/contexts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def intent_path(project: str,intent: str,) -> str: + """Returns a fully-qualified intent string.""" + return "projects/{project}/agent/intents/{intent}".format(project=project, intent=intent, ) + + @staticmethod + def parse_intent_path(path: str) -> Dict[str,str]: + """Parses a intent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/intents/(?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, IntentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the intents 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, IntentsTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, IntentsTransport): + # transport is a IntentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_intents(self, + request: Union[intent.ListIntentsRequest, dict] = None, + *, + parent: str = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListIntentsPager: + r"""Returns the list of all intents in the specified + agent. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListIntentsRequest, dict]): + The request object. The request message for + [Intents.ListIntents][google.cloud.dialogflow.v2.Intents.ListIntents]. + parent (str): + Required. The agent to list all intents from. Format: + ``projects//agent`` or + ``projects//locations//agent``. + + Alternatively, you can specify the environment to list + intents for. Format: + ``projects//agent/environments/`` + or + ``projects//locations//agent/environments/``. + Note: training phrases of the intents will not be + returned for non-draft environment. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.services.intents.pagers.ListIntentsPager: + The response message for + [Intents.ListIntents][google.cloud.dialogflow.v2.Intents.ListIntents]. + + 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, language_code]) + if request is 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 intent.ListIntentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, intent.ListIntentsRequest): + request = intent.ListIntentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if language_code is not None: + request.language_code = language_code + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_intents] + + # Certain 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.ListIntentsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_intent(self, + request: Union[intent.GetIntentRequest, dict] = None, + *, + name: str = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> intent.Intent: + r"""Retrieves the specified intent. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetIntentRequest, dict]): + The request object. The request message for + [Intents.GetIntent][google.cloud.dialogflow.v2.Intents.GetIntent]. + name (str): + Required. The name of the intent. Format: + ``projects//agent/intents/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Intent: + An intent categorizes an end-user's intention for one conversation turn. For + each agent, you define many intents, where your + combined intents can handle a complete conversation. + When an end-user writes or says something, referred + to as an end-user expression or end-user input, + Dialogflow matches the end-user input to the best + intent in your agent. Matching an intent is also + known as intent classification. + + For more information, see the [intent + guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, language_code]) + if request is 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 intent.GetIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, intent.GetIntentRequest): + request = intent.GetIntentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if language_code is not None: + request.language_code = language_code + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_intent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_intent(self, + request: Union[gcd_intent.CreateIntentRequest, dict] = None, + *, + parent: str = None, + intent: gcd_intent.Intent = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_intent.Intent: + r"""Creates an intent in the specified agent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.CreateIntentRequest, dict]): + The request object. The request message for + [Intents.CreateIntent][google.cloud.dialogflow.v2.Intents.CreateIntent]. + parent (str): + Required. The agent to create a intent for. Format: + ``projects//agent``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + intent (google.cloud.dialogflow_v2.types.Intent): + Required. The intent to create. + This corresponds to the ``intent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Intent: + An intent categorizes an end-user's intention for one conversation turn. For + each agent, you define many intents, where your + combined intents can handle a complete conversation. + When an end-user writes or says something, referred + to as an end-user expression or end-user input, + Dialogflow matches the end-user input to the best + intent in your agent. Matching an intent is also + known as intent classification. + + For more information, see the [intent + guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, intent, language_code]) + if request is 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 gcd_intent.CreateIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_intent.CreateIntentRequest): + request = gcd_intent.CreateIntentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if intent is not None: + request.intent = intent + if language_code is not None: + request.language_code = language_code + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_intent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_intent(self, + request: Union[gcd_intent.UpdateIntentRequest, dict] = None, + *, + intent: gcd_intent.Intent = None, + language_code: str = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_intent.Intent: + r"""Updates the specified intent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.UpdateIntentRequest, dict]): + The request object. The request message for + [Intents.UpdateIntent][google.cloud.dialogflow.v2.Intents.UpdateIntent]. + intent (google.cloud.dialogflow_v2.types.Intent): + Required. The intent to update. + This corresponds to the ``intent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Intent: + An intent categorizes an end-user's intention for one conversation turn. For + each agent, you define many intents, where your + combined intents can handle a complete conversation. + When an end-user writes or says something, referred + to as an end-user expression or end-user input, + Dialogflow matches the end-user input to the best + intent in your agent. Matching an intent is also + known as intent classification. + + For more information, see the [intent + guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([intent, language_code, 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 gcd_intent.UpdateIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_intent.UpdateIntentRequest): + request = gcd_intent.UpdateIntentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if intent is not None: + request.intent = intent + if language_code is not None: + request.language_code = language_code + 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_intent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("intent.name", request.intent.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_intent(self, + request: Union[intent.DeleteIntentRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified intent and its direct or indirect followup + intents. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.DeleteIntentRequest, dict]): + The request object. The request message for + [Intents.DeleteIntent][google.cloud.dialogflow.v2.Intents.DeleteIntent]. + name (str): + Required. The name of the intent to delete. If this + intent has direct or indirect followup intents, we also + delete them. Format: + ``projects//agent/intents/``. + + 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 intent.DeleteIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, intent.DeleteIntentRequest): + request = intent.DeleteIntentRequest(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_intent] + + # Certain 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 batch_update_intents(self, + request: Union[intent.BatchUpdateIntentsRequest, dict] = None, + *, + parent: str = None, + intent_batch_uri: str = None, + intent_batch_inline: intent.IntentBatch = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates/Creates multiple intents in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [BatchUpdateIntentsResponse][google.cloud.dialogflow.v2.BatchUpdateIntentsResponse] + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.BatchUpdateIntentsRequest, dict]): + The request object. + parent (str): + Required. The name of the agent to update or create + intents in. Format: ``projects//agent``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + intent_batch_uri (str): + The URI to a Google Cloud Storage + file containing intents to update or + create. The file format can either be a + serialized proto (of IntentBatch type) + or JSON object. Note: The URI must start + with "gs://". + + This corresponds to the ``intent_batch_uri`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + intent_batch_inline (google.cloud.dialogflow_v2.types.IntentBatch): + The collection of intents to update + or create. + + This corresponds to the ``intent_batch_inline`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.dialogflow_v2.types.BatchUpdateIntentsResponse` + The response message for + [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2.Intents.BatchUpdateIntents]. + + """ + # 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, intent_batch_uri, intent_batch_inline]) + if request is 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 intent.BatchUpdateIntentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, intent.BatchUpdateIntentsRequest): + request = intent.BatchUpdateIntentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if intent_batch_uri is not None: + request.intent_batch_uri = intent_batch_uri + if intent_batch_inline is not None: + request.intent_batch_inline = intent_batch_inline + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_update_intents] + + # Certain 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, + intent.BatchUpdateIntentsResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def batch_delete_intents(self, + request: Union[intent.BatchDeleteIntentsRequest, dict] = None, + *, + parent: str = None, + intents: Sequence[intent.Intent] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes intents in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.BatchDeleteIntentsRequest, dict]): + The request object. The request message for + [Intents.BatchDeleteIntents][google.cloud.dialogflow.v2.Intents.BatchDeleteIntents]. + parent (str): + Required. The name of the agent to delete all entities + types for. Format: ``projects//agent``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + intents (Sequence[google.cloud.dialogflow_v2.types.Intent]): + Required. The collection of intents to delete. Only + intent ``name`` must be filled in. + + This corresponds to the ``intents`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, intents]) + if request is 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 intent.BatchDeleteIntentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, intent.BatchDeleteIntentsRequest): + request = intent.BatchDeleteIntentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if intents is not None: + request.intents = intents + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_delete_intents] + + # Certain 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, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "IntentsClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/pagers.py new file mode 100644 index 000000000..8fe983f94 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflow_v2.types import intent + + +class ListIntentsPager: + """A pager for iterating through ``list_intents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListIntentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``intents`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListIntents`` requests and continue to iterate + through the ``intents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListIntentsResponse` + 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[..., intent.ListIntentsResponse], + request: intent.ListIntentsRequest, + response: intent.ListIntentsResponse, + *, + 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.dialogflow_v2.types.ListIntentsRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListIntentsResponse): + 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 = intent.ListIntentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[intent.ListIntentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[intent.Intent]: + for page in self.pages: + yield from page.intents + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListIntentsAsyncPager: + """A pager for iterating through ``list_intents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListIntentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``intents`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListIntents`` requests and continue to iterate + through the ``intents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListIntentsResponse` + 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[intent.ListIntentsResponse]], + request: intent.ListIntentsRequest, + response: intent.ListIntentsResponse, + *, + 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.dialogflow_v2.types.ListIntentsRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListIntentsResponse): + 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 = intent.ListIntentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[intent.ListIntentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[intent.Intent]: + async def async_generator(): + async for page in self.pages: + for response in page.intents: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/__init__.py new file mode 100644 index 000000000..aa8039bba --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/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 IntentsTransport +from .grpc import IntentsGrpcTransport +from .grpc_asyncio import IntentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[IntentsTransport]] +_transport_registry['grpc'] = IntentsGrpcTransport +_transport_registry['grpc_asyncio'] = IntentsGrpcAsyncIOTransport + +__all__ = ( + 'IntentsTransport', + 'IntentsGrpcTransport', + 'IntentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/base.py new file mode 100644 index 000000000..d59f9f450 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/base.py @@ -0,0 +1,240 @@ +# -*- 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.types import intent +from google.cloud.dialogflow_v2.types import intent as gcd_intent +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-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class IntentsTransport(abc.ABC): + """Abstract transport class for Intents.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_intents: gapic_v1.method.wrap_method( + self.list_intents, + default_timeout=None, + client_info=client_info, + ), + self.get_intent: gapic_v1.method.wrap_method( + self.get_intent, + default_timeout=None, + client_info=client_info, + ), + self.create_intent: gapic_v1.method.wrap_method( + self.create_intent, + default_timeout=None, + client_info=client_info, + ), + self.update_intent: gapic_v1.method.wrap_method( + self.update_intent, + default_timeout=None, + client_info=client_info, + ), + self.delete_intent: gapic_v1.method.wrap_method( + self.delete_intent, + default_timeout=None, + client_info=client_info, + ), + self.batch_update_intents: gapic_v1.method.wrap_method( + self.batch_update_intents, + default_timeout=None, + client_info=client_info, + ), + self.batch_delete_intents: gapic_v1.method.wrap_method( + self.batch_delete_intents, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_intents(self) -> Callable[ + [intent.ListIntentsRequest], + Union[ + intent.ListIntentsResponse, + Awaitable[intent.ListIntentsResponse] + ]]: + raise NotImplementedError() + + @property + def get_intent(self) -> Callable[ + [intent.GetIntentRequest], + Union[ + intent.Intent, + Awaitable[intent.Intent] + ]]: + raise NotImplementedError() + + @property + def create_intent(self) -> Callable[ + [gcd_intent.CreateIntentRequest], + Union[ + gcd_intent.Intent, + Awaitable[gcd_intent.Intent] + ]]: + raise NotImplementedError() + + @property + def update_intent(self) -> Callable[ + [gcd_intent.UpdateIntentRequest], + Union[ + gcd_intent.Intent, + Awaitable[gcd_intent.Intent] + ]]: + raise NotImplementedError() + + @property + def delete_intent(self) -> Callable[ + [intent.DeleteIntentRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def batch_update_intents(self) -> Callable[ + [intent.BatchUpdateIntentsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def batch_delete_intents(self) -> Callable[ + [intent.BatchDeleteIntentsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'IntentsTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/grpc.py new file mode 100644 index 000000000..181b51b82 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/grpc.py @@ -0,0 +1,473 @@ +# -*- 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 +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import intent +from google.cloud.dialogflow_v2.types import intent as gcd_intent +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import IntentsTransport, DEFAULT_CLIENT_INFO + + +class IntentsGrpcTransport(IntentsTransport): + """gRPC backend transport for Intents. + + Service for managing [Intents][google.cloud.dialogflow.v2.Intent]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 = 'dialogflow.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 list_intents(self) -> Callable[ + [intent.ListIntentsRequest], + intent.ListIntentsResponse]: + r"""Return a callable for the list intents method over gRPC. + + Returns the list of all intents in the specified + agent. + + Returns: + Callable[[~.ListIntentsRequest], + ~.ListIntentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_intents' not in self._stubs: + self._stubs['list_intents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Intents/ListIntents', + request_serializer=intent.ListIntentsRequest.serialize, + response_deserializer=intent.ListIntentsResponse.deserialize, + ) + return self._stubs['list_intents'] + + @property + def get_intent(self) -> Callable[ + [intent.GetIntentRequest], + intent.Intent]: + r"""Return a callable for the get intent method over gRPC. + + Retrieves the specified intent. + + Returns: + Callable[[~.GetIntentRequest], + ~.Intent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_intent' not in self._stubs: + self._stubs['get_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Intents/GetIntent', + request_serializer=intent.GetIntentRequest.serialize, + response_deserializer=intent.Intent.deserialize, + ) + return self._stubs['get_intent'] + + @property + def create_intent(self) -> Callable[ + [gcd_intent.CreateIntentRequest], + gcd_intent.Intent]: + r"""Return a callable for the create intent method over gRPC. + + Creates an intent in the specified agent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.CreateIntentRequest], + ~.Intent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_intent' not in self._stubs: + self._stubs['create_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Intents/CreateIntent', + request_serializer=gcd_intent.CreateIntentRequest.serialize, + response_deserializer=gcd_intent.Intent.deserialize, + ) + return self._stubs['create_intent'] + + @property + def update_intent(self) -> Callable[ + [gcd_intent.UpdateIntentRequest], + gcd_intent.Intent]: + r"""Return a callable for the update intent method over gRPC. + + Updates the specified intent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.UpdateIntentRequest], + ~.Intent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_intent' not in self._stubs: + self._stubs['update_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Intents/UpdateIntent', + request_serializer=gcd_intent.UpdateIntentRequest.serialize, + response_deserializer=gcd_intent.Intent.deserialize, + ) + return self._stubs['update_intent'] + + @property + def delete_intent(self) -> Callable[ + [intent.DeleteIntentRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete intent method over gRPC. + + Deletes the specified intent and its direct or indirect followup + intents. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.DeleteIntentRequest], + ~.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_intent' not in self._stubs: + self._stubs['delete_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Intents/DeleteIntent', + request_serializer=intent.DeleteIntentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_intent'] + + @property + def batch_update_intents(self) -> Callable[ + [intent.BatchUpdateIntentsRequest], + operations_pb2.Operation]: + r"""Return a callable for the batch update intents method over gRPC. + + Updates/Creates multiple intents in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [BatchUpdateIntentsResponse][google.cloud.dialogflow.v2.BatchUpdateIntentsResponse] + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.BatchUpdateIntentsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_update_intents' not in self._stubs: + self._stubs['batch_update_intents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Intents/BatchUpdateIntents', + request_serializer=intent.BatchUpdateIntentsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_update_intents'] + + @property + def batch_delete_intents(self) -> Callable[ + [intent.BatchDeleteIntentsRequest], + operations_pb2.Operation]: + r"""Return a callable for the batch delete intents method over gRPC. + + Deletes intents in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.BatchDeleteIntentsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_delete_intents' not in self._stubs: + self._stubs['batch_delete_intents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Intents/BatchDeleteIntents', + request_serializer=intent.BatchDeleteIntentsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_delete_intents'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'IntentsGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/grpc_asyncio.py new file mode 100644 index 000000000..c464ea162 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/grpc_asyncio.py @@ -0,0 +1,477 @@ +# -*- 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 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import intent +from google.cloud.dialogflow_v2.types import intent as gcd_intent +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import IntentsTransport, DEFAULT_CLIENT_INFO +from .grpc import IntentsGrpcTransport + + +class IntentsGrpcAsyncIOTransport(IntentsTransport): + """gRPC AsyncIO backend transport for Intents. + + Service for managing [Intents][google.cloud.dialogflow.v2.Intent]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 list_intents(self) -> Callable[ + [intent.ListIntentsRequest], + Awaitable[intent.ListIntentsResponse]]: + r"""Return a callable for the list intents method over gRPC. + + Returns the list of all intents in the specified + agent. + + Returns: + Callable[[~.ListIntentsRequest], + Awaitable[~.ListIntentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_intents' not in self._stubs: + self._stubs['list_intents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Intents/ListIntents', + request_serializer=intent.ListIntentsRequest.serialize, + response_deserializer=intent.ListIntentsResponse.deserialize, + ) + return self._stubs['list_intents'] + + @property + def get_intent(self) -> Callable[ + [intent.GetIntentRequest], + Awaitable[intent.Intent]]: + r"""Return a callable for the get intent method over gRPC. + + Retrieves the specified intent. + + Returns: + Callable[[~.GetIntentRequest], + Awaitable[~.Intent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_intent' not in self._stubs: + self._stubs['get_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Intents/GetIntent', + request_serializer=intent.GetIntentRequest.serialize, + response_deserializer=intent.Intent.deserialize, + ) + return self._stubs['get_intent'] + + @property + def create_intent(self) -> Callable[ + [gcd_intent.CreateIntentRequest], + Awaitable[gcd_intent.Intent]]: + r"""Return a callable for the create intent method over gRPC. + + Creates an intent in the specified agent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.CreateIntentRequest], + Awaitable[~.Intent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_intent' not in self._stubs: + self._stubs['create_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Intents/CreateIntent', + request_serializer=gcd_intent.CreateIntentRequest.serialize, + response_deserializer=gcd_intent.Intent.deserialize, + ) + return self._stubs['create_intent'] + + @property + def update_intent(self) -> Callable[ + [gcd_intent.UpdateIntentRequest], + Awaitable[gcd_intent.Intent]]: + r"""Return a callable for the update intent method over gRPC. + + Updates the specified intent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.UpdateIntentRequest], + Awaitable[~.Intent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_intent' not in self._stubs: + self._stubs['update_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Intents/UpdateIntent', + request_serializer=gcd_intent.UpdateIntentRequest.serialize, + response_deserializer=gcd_intent.Intent.deserialize, + ) + return self._stubs['update_intent'] + + @property + def delete_intent(self) -> Callable[ + [intent.DeleteIntentRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete intent method over gRPC. + + Deletes the specified intent and its direct or indirect followup + intents. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.DeleteIntentRequest], + 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_intent' not in self._stubs: + self._stubs['delete_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Intents/DeleteIntent', + request_serializer=intent.DeleteIntentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_intent'] + + @property + def batch_update_intents(self) -> Callable[ + [intent.BatchUpdateIntentsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the batch update intents method over gRPC. + + Updates/Creates multiple intents in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [BatchUpdateIntentsResponse][google.cloud.dialogflow.v2.BatchUpdateIntentsResponse] + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.BatchUpdateIntentsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_update_intents' not in self._stubs: + self._stubs['batch_update_intents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Intents/BatchUpdateIntents', + request_serializer=intent.BatchUpdateIntentsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_update_intents'] + + @property + def batch_delete_intents(self) -> Callable[ + [intent.BatchDeleteIntentsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the batch delete intents method over gRPC. + + Deletes intents in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.BatchDeleteIntentsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_delete_intents' not in self._stubs: + self._stubs['batch_delete_intents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Intents/BatchDeleteIntents', + request_serializer=intent.BatchDeleteIntentsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_delete_intents'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'IntentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/__init__.py new file mode 100644 index 000000000..670d8e66d --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/__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 KnowledgeBasesClient +from .async_client import KnowledgeBasesAsyncClient + +__all__ = ( + 'KnowledgeBasesClient', + 'KnowledgeBasesAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/async_client.py new file mode 100644 index 000000000..9b42d11a0 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/async_client.py @@ -0,0 +1,608 @@ +# -*- 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 + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2.services.knowledge_bases import pagers +from google.cloud.dialogflow_v2.types import knowledge_base +from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import KnowledgeBasesGrpcAsyncIOTransport +from .client import KnowledgeBasesClient + + +class KnowledgeBasesAsyncClient: + """Service for managing + [KnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBase]. + """ + + _client: KnowledgeBasesClient + + DEFAULT_ENDPOINT = KnowledgeBasesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = KnowledgeBasesClient.DEFAULT_MTLS_ENDPOINT + + knowledge_base_path = staticmethod(KnowledgeBasesClient.knowledge_base_path) + parse_knowledge_base_path = staticmethod(KnowledgeBasesClient.parse_knowledge_base_path) + common_billing_account_path = staticmethod(KnowledgeBasesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(KnowledgeBasesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(KnowledgeBasesClient.common_folder_path) + parse_common_folder_path = staticmethod(KnowledgeBasesClient.parse_common_folder_path) + common_organization_path = staticmethod(KnowledgeBasesClient.common_organization_path) + parse_common_organization_path = staticmethod(KnowledgeBasesClient.parse_common_organization_path) + common_project_path = staticmethod(KnowledgeBasesClient.common_project_path) + parse_common_project_path = staticmethod(KnowledgeBasesClient.parse_common_project_path) + common_location_path = staticmethod(KnowledgeBasesClient.common_location_path) + parse_common_location_path = staticmethod(KnowledgeBasesClient.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: + KnowledgeBasesAsyncClient: The constructed client. + """ + return KnowledgeBasesClient.from_service_account_info.__func__(KnowledgeBasesAsyncClient, 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: + KnowledgeBasesAsyncClient: The constructed client. + """ + return KnowledgeBasesClient.from_service_account_file.__func__(KnowledgeBasesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> KnowledgeBasesTransport: + """Returns the transport used by the client instance. + + Returns: + KnowledgeBasesTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(KnowledgeBasesClient).get_transport_class, type(KnowledgeBasesClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, KnowledgeBasesTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the knowledge bases 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, ~.KnowledgeBasesTransport]): 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 = KnowledgeBasesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_knowledge_bases(self, + request: Union[knowledge_base.ListKnowledgeBasesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListKnowledgeBasesAsyncPager: + r"""Returns the list of all knowledge bases of the + specified agent. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListKnowledgeBasesRequest, dict]): + The request object. Request message for + [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBases.ListKnowledgeBases]. + parent (:class:`str`): + Required. The project to list of knowledge bases for. + Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.services.knowledge_bases.pagers.ListKnowledgeBasesAsyncPager: + Response message for + [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBases.ListKnowledgeBases]. + + 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 = knowledge_base.ListKnowledgeBasesRequest(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_knowledge_bases, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListKnowledgeBasesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_knowledge_base(self, + request: Union[knowledge_base.GetKnowledgeBaseRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> knowledge_base.KnowledgeBase: + r"""Retrieves the specified knowledge base. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetKnowledgeBaseRequest, dict]): + The request object. Request message for + [KnowledgeBases.GetKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.GetKnowledgeBase]. + name (:class:`str`): + Required. The name of the knowledge base to retrieve. + Format + ``projects//locations//knowledgeBases/``. + + 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.dialogflow_v2.types.KnowledgeBase: + A knowledge base represents a collection of knowledge documents that you + provide to Dialogflow. Your knowledge documents + contain information that may be useful during + conversations with end-users. Some Dialogflow + features use knowledge bases when looking for a + response to an end-user input. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases resource is + deprecated; only use projects.knowledgeBases. + + """ + # 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 = knowledge_base.GetKnowledgeBaseRequest(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_knowledge_base, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_knowledge_base(self, + request: Union[gcd_knowledge_base.CreateKnowledgeBaseRequest, dict] = None, + *, + parent: str = None, + knowledge_base: gcd_knowledge_base.KnowledgeBase = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_knowledge_base.KnowledgeBase: + r"""Creates a knowledge base. + + Args: + request (Union[google.cloud.dialogflow_v2.types.CreateKnowledgeBaseRequest, dict]): + The request object. Request message for + [KnowledgeBases.CreateKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.CreateKnowledgeBase]. + parent (:class:`str`): + Required. The project to create a knowledge base for. + Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + knowledge_base (:class:`google.cloud.dialogflow_v2.types.KnowledgeBase`): + Required. The knowledge base to + create. + + This corresponds to the ``knowledge_base`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.KnowledgeBase: + A knowledge base represents a collection of knowledge documents that you + provide to Dialogflow. Your knowledge documents + contain information that may be useful during + conversations with end-users. Some Dialogflow + features use knowledge bases when looking for a + response to an end-user input. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases resource is + deprecated; only use projects.knowledgeBases. + + """ + # 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, knowledge_base]) + if request is 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 = gcd_knowledge_base.CreateKnowledgeBaseRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if knowledge_base is not None: + request.knowledge_base = knowledge_base + + # 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_knowledge_base, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_knowledge_base(self, + request: Union[knowledge_base.DeleteKnowledgeBaseRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified knowledge base. + + Args: + request (Union[google.cloud.dialogflow_v2.types.DeleteKnowledgeBaseRequest, dict]): + The request object. Request message for + [KnowledgeBases.DeleteKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.DeleteKnowledgeBase]. + name (:class:`str`): + Required. The name of the knowledge base to delete. + Format: + ``projects//locations//knowledgeBases/``. + + 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 = knowledge_base.DeleteKnowledgeBaseRequest(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_knowledge_base, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def update_knowledge_base(self, + request: Union[gcd_knowledge_base.UpdateKnowledgeBaseRequest, dict] = None, + *, + knowledge_base: gcd_knowledge_base.KnowledgeBase = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_knowledge_base.KnowledgeBase: + r"""Updates the specified knowledge base. + + Args: + request (Union[google.cloud.dialogflow_v2.types.UpdateKnowledgeBaseRequest, dict]): + The request object. Request message for + [KnowledgeBases.UpdateKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.UpdateKnowledgeBase]. + knowledge_base (:class:`google.cloud.dialogflow_v2.types.KnowledgeBase`): + Required. The knowledge base to + update. + + This corresponds to the ``knowledge_base`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Not specified means ``update all``. Currently, + only ``display_name`` can be updated, an InvalidArgument + will be returned for attempting to update other 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.dialogflow_v2.types.KnowledgeBase: + A knowledge base represents a collection of knowledge documents that you + provide to Dialogflow. Your knowledge documents + contain information that may be useful during + conversations with end-users. Some Dialogflow + features use knowledge bases when looking for a + response to an end-user input. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases resource is + deprecated; only use projects.knowledgeBases. + + """ + # 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([knowledge_base, 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 = gcd_knowledge_base.UpdateKnowledgeBaseRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if knowledge_base is not None: + request.knowledge_base = knowledge_base + 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_knowledge_base, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("knowledge_base.name", request.knowledge_base.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "KnowledgeBasesAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/client.py new file mode 100644 index 000000000..2427e29fa --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/client.py @@ -0,0 +1,806 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2.services.knowledge_bases import pagers +from google.cloud.dialogflow_v2.types import knowledge_base +from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import KnowledgeBasesGrpcTransport +from .transports.grpc_asyncio import KnowledgeBasesGrpcAsyncIOTransport + + +class KnowledgeBasesClientMeta(type): + """Metaclass for the KnowledgeBases 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[KnowledgeBasesTransport]] + _transport_registry["grpc"] = KnowledgeBasesGrpcTransport + _transport_registry["grpc_asyncio"] = KnowledgeBasesGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[KnowledgeBasesTransport]: + """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 KnowledgeBasesClient(metaclass=KnowledgeBasesClientMeta): + """Service for managing + [KnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBase]. + """ + + @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 = "dialogflow.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: + KnowledgeBasesClient: 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: + KnowledgeBasesClient: 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) -> KnowledgeBasesTransport: + """Returns the transport used by the client instance. + + Returns: + KnowledgeBasesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def knowledge_base_path(project: str,knowledge_base: str,) -> str: + """Returns a fully-qualified knowledge_base string.""" + return "projects/{project}/knowledgeBases/{knowledge_base}".format(project=project, knowledge_base=knowledge_base, ) + + @staticmethod + def parse_knowledge_base_path(path: str) -> Dict[str,str]: + """Parses a knowledge_base path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/knowledgeBases/(?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, KnowledgeBasesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the knowledge bases 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, KnowledgeBasesTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, KnowledgeBasesTransport): + # transport is a KnowledgeBasesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_knowledge_bases(self, + request: Union[knowledge_base.ListKnowledgeBasesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListKnowledgeBasesPager: + r"""Returns the list of all knowledge bases of the + specified agent. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListKnowledgeBasesRequest, dict]): + The request object. Request message for + [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBases.ListKnowledgeBases]. + parent (str): + Required. The project to list of knowledge bases for. + Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.services.knowledge_bases.pagers.ListKnowledgeBasesPager: + Response message for + [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBases.ListKnowledgeBases]. + + 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 knowledge_base.ListKnowledgeBasesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, knowledge_base.ListKnowledgeBasesRequest): + request = knowledge_base.ListKnowledgeBasesRequest(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_knowledge_bases] + + # Certain 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.ListKnowledgeBasesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_knowledge_base(self, + request: Union[knowledge_base.GetKnowledgeBaseRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> knowledge_base.KnowledgeBase: + r"""Retrieves the specified knowledge base. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetKnowledgeBaseRequest, dict]): + The request object. Request message for + [KnowledgeBases.GetKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.GetKnowledgeBase]. + name (str): + Required. The name of the knowledge base to retrieve. + Format + ``projects//locations//knowledgeBases/``. + + 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.dialogflow_v2.types.KnowledgeBase: + A knowledge base represents a collection of knowledge documents that you + provide to Dialogflow. Your knowledge documents + contain information that may be useful during + conversations with end-users. Some Dialogflow + features use knowledge bases when looking for a + response to an end-user input. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases resource is + deprecated; only use projects.knowledgeBases. + + """ + # 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 knowledge_base.GetKnowledgeBaseRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, knowledge_base.GetKnowledgeBaseRequest): + request = knowledge_base.GetKnowledgeBaseRequest(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_knowledge_base] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_knowledge_base(self, + request: Union[gcd_knowledge_base.CreateKnowledgeBaseRequest, dict] = None, + *, + parent: str = None, + knowledge_base: gcd_knowledge_base.KnowledgeBase = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_knowledge_base.KnowledgeBase: + r"""Creates a knowledge base. + + Args: + request (Union[google.cloud.dialogflow_v2.types.CreateKnowledgeBaseRequest, dict]): + The request object. Request message for + [KnowledgeBases.CreateKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.CreateKnowledgeBase]. + parent (str): + Required. The project to create a knowledge base for. + Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + knowledge_base (google.cloud.dialogflow_v2.types.KnowledgeBase): + Required. The knowledge base to + create. + + This corresponds to the ``knowledge_base`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.KnowledgeBase: + A knowledge base represents a collection of knowledge documents that you + provide to Dialogflow. Your knowledge documents + contain information that may be useful during + conversations with end-users. Some Dialogflow + features use knowledge bases when looking for a + response to an end-user input. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases resource is + deprecated; only use projects.knowledgeBases. + + """ + # 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, knowledge_base]) + if request is 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 gcd_knowledge_base.CreateKnowledgeBaseRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_knowledge_base.CreateKnowledgeBaseRequest): + request = gcd_knowledge_base.CreateKnowledgeBaseRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if knowledge_base is not None: + request.knowledge_base = knowledge_base + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_knowledge_base] + + # Certain 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 delete_knowledge_base(self, + request: Union[knowledge_base.DeleteKnowledgeBaseRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified knowledge base. + + Args: + request (Union[google.cloud.dialogflow_v2.types.DeleteKnowledgeBaseRequest, dict]): + The request object. Request message for + [KnowledgeBases.DeleteKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.DeleteKnowledgeBase]. + name (str): + Required. The name of the knowledge base to delete. + Format: + ``projects//locations//knowledgeBases/``. + + 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 knowledge_base.DeleteKnowledgeBaseRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, knowledge_base.DeleteKnowledgeBaseRequest): + request = knowledge_base.DeleteKnowledgeBaseRequest(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_knowledge_base] + + # Certain 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 update_knowledge_base(self, + request: Union[gcd_knowledge_base.UpdateKnowledgeBaseRequest, dict] = None, + *, + knowledge_base: gcd_knowledge_base.KnowledgeBase = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_knowledge_base.KnowledgeBase: + r"""Updates the specified knowledge base. + + Args: + request (Union[google.cloud.dialogflow_v2.types.UpdateKnowledgeBaseRequest, dict]): + The request object. Request message for + [KnowledgeBases.UpdateKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.UpdateKnowledgeBase]. + knowledge_base (google.cloud.dialogflow_v2.types.KnowledgeBase): + Required. The knowledge base to + update. + + This corresponds to the ``knowledge_base`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Not specified means ``update all``. Currently, + only ``display_name`` can be updated, an InvalidArgument + will be returned for attempting to update other 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.dialogflow_v2.types.KnowledgeBase: + A knowledge base represents a collection of knowledge documents that you + provide to Dialogflow. Your knowledge documents + contain information that may be useful during + conversations with end-users. Some Dialogflow + features use knowledge bases when looking for a + response to an end-user input. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases resource is + deprecated; only use projects.knowledgeBases. + + """ + # 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([knowledge_base, 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 gcd_knowledge_base.UpdateKnowledgeBaseRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_knowledge_base.UpdateKnowledgeBaseRequest): + request = gcd_knowledge_base.UpdateKnowledgeBaseRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if knowledge_base is not None: + request.knowledge_base = knowledge_base + 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_knowledge_base] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("knowledge_base.name", request.knowledge_base.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "KnowledgeBasesClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/pagers.py new file mode 100644 index 000000000..4a1d572f2 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflow_v2.types import knowledge_base + + +class ListKnowledgeBasesPager: + """A pager for iterating through ``list_knowledge_bases`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListKnowledgeBasesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``knowledge_bases`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListKnowledgeBases`` requests and continue to iterate + through the ``knowledge_bases`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListKnowledgeBasesResponse` + 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[..., knowledge_base.ListKnowledgeBasesResponse], + request: knowledge_base.ListKnowledgeBasesRequest, + response: knowledge_base.ListKnowledgeBasesResponse, + *, + 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.dialogflow_v2.types.ListKnowledgeBasesRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListKnowledgeBasesResponse): + 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 = knowledge_base.ListKnowledgeBasesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[knowledge_base.ListKnowledgeBasesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[knowledge_base.KnowledgeBase]: + for page in self.pages: + yield from page.knowledge_bases + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListKnowledgeBasesAsyncPager: + """A pager for iterating through ``list_knowledge_bases`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListKnowledgeBasesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``knowledge_bases`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListKnowledgeBases`` requests and continue to iterate + through the ``knowledge_bases`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListKnowledgeBasesResponse` + 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[knowledge_base.ListKnowledgeBasesResponse]], + request: knowledge_base.ListKnowledgeBasesRequest, + response: knowledge_base.ListKnowledgeBasesResponse, + *, + 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.dialogflow_v2.types.ListKnowledgeBasesRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListKnowledgeBasesResponse): + 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 = knowledge_base.ListKnowledgeBasesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[knowledge_base.ListKnowledgeBasesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[knowledge_base.KnowledgeBase]: + async def async_generator(): + async for page in self.pages: + for response in page.knowledge_bases: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/__init__.py new file mode 100644 index 000000000..c04ef7c9f --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/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 KnowledgeBasesTransport +from .grpc import KnowledgeBasesGrpcTransport +from .grpc_asyncio import KnowledgeBasesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[KnowledgeBasesTransport]] +_transport_registry['grpc'] = KnowledgeBasesGrpcTransport +_transport_registry['grpc_asyncio'] = KnowledgeBasesGrpcAsyncIOTransport + +__all__ = ( + 'KnowledgeBasesTransport', + 'KnowledgeBasesGrpcTransport', + 'KnowledgeBasesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/base.py new file mode 100644 index 000000000..d7e62fe5e --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/base.py @@ -0,0 +1,205 @@ +# -*- 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.types import knowledge_base +from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base +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-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class KnowledgeBasesTransport(abc.ABC): + """Abstract transport class for KnowledgeBases.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_knowledge_bases: gapic_v1.method.wrap_method( + self.list_knowledge_bases, + default_timeout=None, + client_info=client_info, + ), + self.get_knowledge_base: gapic_v1.method.wrap_method( + self.get_knowledge_base, + default_timeout=None, + client_info=client_info, + ), + self.create_knowledge_base: gapic_v1.method.wrap_method( + self.create_knowledge_base, + default_timeout=None, + client_info=client_info, + ), + self.delete_knowledge_base: gapic_v1.method.wrap_method( + self.delete_knowledge_base, + default_timeout=None, + client_info=client_info, + ), + self.update_knowledge_base: gapic_v1.method.wrap_method( + self.update_knowledge_base, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_knowledge_bases(self) -> Callable[ + [knowledge_base.ListKnowledgeBasesRequest], + Union[ + knowledge_base.ListKnowledgeBasesResponse, + Awaitable[knowledge_base.ListKnowledgeBasesResponse] + ]]: + raise NotImplementedError() + + @property + def get_knowledge_base(self) -> Callable[ + [knowledge_base.GetKnowledgeBaseRequest], + Union[ + knowledge_base.KnowledgeBase, + Awaitable[knowledge_base.KnowledgeBase] + ]]: + raise NotImplementedError() + + @property + def create_knowledge_base(self) -> Callable[ + [gcd_knowledge_base.CreateKnowledgeBaseRequest], + Union[ + gcd_knowledge_base.KnowledgeBase, + Awaitable[gcd_knowledge_base.KnowledgeBase] + ]]: + raise NotImplementedError() + + @property + def delete_knowledge_base(self) -> Callable[ + [knowledge_base.DeleteKnowledgeBaseRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_knowledge_base(self) -> Callable[ + [gcd_knowledge_base.UpdateKnowledgeBaseRequest], + Union[ + gcd_knowledge_base.KnowledgeBase, + Awaitable[gcd_knowledge_base.KnowledgeBase] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'KnowledgeBasesTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc.py new file mode 100644 index 000000000..7a144a23f --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc.py @@ -0,0 +1,362 @@ +# -*- 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 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import knowledge_base +from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base +from google.protobuf import empty_pb2 # type: ignore +from .base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO + + +class KnowledgeBasesGrpcTransport(KnowledgeBasesTransport): + """gRPC backend transport for KnowledgeBases. + + Service for managing + [KnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBase]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 = 'dialogflow.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 list_knowledge_bases(self) -> Callable[ + [knowledge_base.ListKnowledgeBasesRequest], + knowledge_base.ListKnowledgeBasesResponse]: + r"""Return a callable for the list knowledge bases method over gRPC. + + Returns the list of all knowledge bases of the + specified agent. + + Returns: + Callable[[~.ListKnowledgeBasesRequest], + ~.ListKnowledgeBasesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_knowledge_bases' not in self._stubs: + self._stubs['list_knowledge_bases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.KnowledgeBases/ListKnowledgeBases', + request_serializer=knowledge_base.ListKnowledgeBasesRequest.serialize, + response_deserializer=knowledge_base.ListKnowledgeBasesResponse.deserialize, + ) + return self._stubs['list_knowledge_bases'] + + @property + def get_knowledge_base(self) -> Callable[ + [knowledge_base.GetKnowledgeBaseRequest], + knowledge_base.KnowledgeBase]: + r"""Return a callable for the get knowledge base method over gRPC. + + Retrieves the specified knowledge base. + + Returns: + Callable[[~.GetKnowledgeBaseRequest], + ~.KnowledgeBase]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_knowledge_base' not in self._stubs: + self._stubs['get_knowledge_base'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.KnowledgeBases/GetKnowledgeBase', + request_serializer=knowledge_base.GetKnowledgeBaseRequest.serialize, + response_deserializer=knowledge_base.KnowledgeBase.deserialize, + ) + return self._stubs['get_knowledge_base'] + + @property + def create_knowledge_base(self) -> Callable[ + [gcd_knowledge_base.CreateKnowledgeBaseRequest], + gcd_knowledge_base.KnowledgeBase]: + r"""Return a callable for the create knowledge base method over gRPC. + + Creates a knowledge base. + + Returns: + Callable[[~.CreateKnowledgeBaseRequest], + ~.KnowledgeBase]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_knowledge_base' not in self._stubs: + self._stubs['create_knowledge_base'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.KnowledgeBases/CreateKnowledgeBase', + request_serializer=gcd_knowledge_base.CreateKnowledgeBaseRequest.serialize, + response_deserializer=gcd_knowledge_base.KnowledgeBase.deserialize, + ) + return self._stubs['create_knowledge_base'] + + @property + def delete_knowledge_base(self) -> Callable[ + [knowledge_base.DeleteKnowledgeBaseRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete knowledge base method over gRPC. + + Deletes the specified knowledge base. + + Returns: + Callable[[~.DeleteKnowledgeBaseRequest], + ~.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_knowledge_base' not in self._stubs: + self._stubs['delete_knowledge_base'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.KnowledgeBases/DeleteKnowledgeBase', + request_serializer=knowledge_base.DeleteKnowledgeBaseRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_knowledge_base'] + + @property + def update_knowledge_base(self) -> Callable[ + [gcd_knowledge_base.UpdateKnowledgeBaseRequest], + gcd_knowledge_base.KnowledgeBase]: + r"""Return a callable for the update knowledge base method over gRPC. + + Updates the specified knowledge base. + + Returns: + Callable[[~.UpdateKnowledgeBaseRequest], + ~.KnowledgeBase]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_knowledge_base' not in self._stubs: + self._stubs['update_knowledge_base'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.KnowledgeBases/UpdateKnowledgeBase', + request_serializer=gcd_knowledge_base.UpdateKnowledgeBaseRequest.serialize, + response_deserializer=gcd_knowledge_base.KnowledgeBase.deserialize, + ) + return self._stubs['update_knowledge_base'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'KnowledgeBasesGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc_asyncio.py new file mode 100644 index 000000000..dc61b4f82 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc_asyncio.py @@ -0,0 +1,366 @@ +# -*- 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 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import knowledge_base +from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base +from google.protobuf import empty_pb2 # type: ignore +from .base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO +from .grpc import KnowledgeBasesGrpcTransport + + +class KnowledgeBasesGrpcAsyncIOTransport(KnowledgeBasesTransport): + """gRPC AsyncIO backend transport for KnowledgeBases. + + Service for managing + [KnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBase]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 list_knowledge_bases(self) -> Callable[ + [knowledge_base.ListKnowledgeBasesRequest], + Awaitable[knowledge_base.ListKnowledgeBasesResponse]]: + r"""Return a callable for the list knowledge bases method over gRPC. + + Returns the list of all knowledge bases of the + specified agent. + + Returns: + Callable[[~.ListKnowledgeBasesRequest], + Awaitable[~.ListKnowledgeBasesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_knowledge_bases' not in self._stubs: + self._stubs['list_knowledge_bases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.KnowledgeBases/ListKnowledgeBases', + request_serializer=knowledge_base.ListKnowledgeBasesRequest.serialize, + response_deserializer=knowledge_base.ListKnowledgeBasesResponse.deserialize, + ) + return self._stubs['list_knowledge_bases'] + + @property + def get_knowledge_base(self) -> Callable[ + [knowledge_base.GetKnowledgeBaseRequest], + Awaitable[knowledge_base.KnowledgeBase]]: + r"""Return a callable for the get knowledge base method over gRPC. + + Retrieves the specified knowledge base. + + Returns: + Callable[[~.GetKnowledgeBaseRequest], + Awaitable[~.KnowledgeBase]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_knowledge_base' not in self._stubs: + self._stubs['get_knowledge_base'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.KnowledgeBases/GetKnowledgeBase', + request_serializer=knowledge_base.GetKnowledgeBaseRequest.serialize, + response_deserializer=knowledge_base.KnowledgeBase.deserialize, + ) + return self._stubs['get_knowledge_base'] + + @property + def create_knowledge_base(self) -> Callable[ + [gcd_knowledge_base.CreateKnowledgeBaseRequest], + Awaitable[gcd_knowledge_base.KnowledgeBase]]: + r"""Return a callable for the create knowledge base method over gRPC. + + Creates a knowledge base. + + Returns: + Callable[[~.CreateKnowledgeBaseRequest], + Awaitable[~.KnowledgeBase]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_knowledge_base' not in self._stubs: + self._stubs['create_knowledge_base'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.KnowledgeBases/CreateKnowledgeBase', + request_serializer=gcd_knowledge_base.CreateKnowledgeBaseRequest.serialize, + response_deserializer=gcd_knowledge_base.KnowledgeBase.deserialize, + ) + return self._stubs['create_knowledge_base'] + + @property + def delete_knowledge_base(self) -> Callable[ + [knowledge_base.DeleteKnowledgeBaseRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete knowledge base method over gRPC. + + Deletes the specified knowledge base. + + Returns: + Callable[[~.DeleteKnowledgeBaseRequest], + 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_knowledge_base' not in self._stubs: + self._stubs['delete_knowledge_base'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.KnowledgeBases/DeleteKnowledgeBase', + request_serializer=knowledge_base.DeleteKnowledgeBaseRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_knowledge_base'] + + @property + def update_knowledge_base(self) -> Callable[ + [gcd_knowledge_base.UpdateKnowledgeBaseRequest], + Awaitable[gcd_knowledge_base.KnowledgeBase]]: + r"""Return a callable for the update knowledge base method over gRPC. + + Updates the specified knowledge base. + + Returns: + Callable[[~.UpdateKnowledgeBaseRequest], + Awaitable[~.KnowledgeBase]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_knowledge_base' not in self._stubs: + self._stubs['update_knowledge_base'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.KnowledgeBases/UpdateKnowledgeBase', + request_serializer=gcd_knowledge_base.UpdateKnowledgeBaseRequest.serialize, + response_deserializer=gcd_knowledge_base.KnowledgeBase.deserialize, + ) + return self._stubs['update_knowledge_base'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'KnowledgeBasesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/__init__.py new file mode 100644 index 000000000..376e9e7d4 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/__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 ParticipantsClient +from .async_client import ParticipantsAsyncClient + +__all__ = ( + 'ParticipantsClient', + 'ParticipantsAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/async_client.py new file mode 100644 index 000000000..e27cd8b99 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/async_client.py @@ -0,0 +1,773 @@ +# -*- 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 + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2.services.participants import pagers +from google.cloud.dialogflow_v2.types import participant +from google.cloud.dialogflow_v2.types import participant as gcd_participant +from google.cloud.dialogflow_v2.types import session +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ParticipantsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ParticipantsGrpcAsyncIOTransport +from .client import ParticipantsClient + + +class ParticipantsAsyncClient: + """Service for managing + [Participants][google.cloud.dialogflow.v2.Participant]. + """ + + _client: ParticipantsClient + + DEFAULT_ENDPOINT = ParticipantsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ParticipantsClient.DEFAULT_MTLS_ENDPOINT + + context_path = staticmethod(ParticipantsClient.context_path) + parse_context_path = staticmethod(ParticipantsClient.parse_context_path) + intent_path = staticmethod(ParticipantsClient.intent_path) + parse_intent_path = staticmethod(ParticipantsClient.parse_intent_path) + message_path = staticmethod(ParticipantsClient.message_path) + parse_message_path = staticmethod(ParticipantsClient.parse_message_path) + participant_path = staticmethod(ParticipantsClient.participant_path) + parse_participant_path = staticmethod(ParticipantsClient.parse_participant_path) + session_entity_type_path = staticmethod(ParticipantsClient.session_entity_type_path) + parse_session_entity_type_path = staticmethod(ParticipantsClient.parse_session_entity_type_path) + common_billing_account_path = staticmethod(ParticipantsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ParticipantsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ParticipantsClient.common_folder_path) + parse_common_folder_path = staticmethod(ParticipantsClient.parse_common_folder_path) + common_organization_path = staticmethod(ParticipantsClient.common_organization_path) + parse_common_organization_path = staticmethod(ParticipantsClient.parse_common_organization_path) + common_project_path = staticmethod(ParticipantsClient.common_project_path) + parse_common_project_path = staticmethod(ParticipantsClient.parse_common_project_path) + common_location_path = staticmethod(ParticipantsClient.common_location_path) + parse_common_location_path = staticmethod(ParticipantsClient.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: + ParticipantsAsyncClient: The constructed client. + """ + return ParticipantsClient.from_service_account_info.__func__(ParticipantsAsyncClient, 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: + ParticipantsAsyncClient: The constructed client. + """ + return ParticipantsClient.from_service_account_file.__func__(ParticipantsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ParticipantsTransport: + """Returns the transport used by the client instance. + + Returns: + ParticipantsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ParticipantsClient).get_transport_class, type(ParticipantsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ParticipantsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the participants 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, ~.ParticipantsTransport]): 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 = ParticipantsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_participant(self, + request: Union[gcd_participant.CreateParticipantRequest, dict] = None, + *, + parent: str = None, + participant: gcd_participant.Participant = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_participant.Participant: + r"""Creates a new participant in a conversation. + + Args: + request (Union[google.cloud.dialogflow_v2.types.CreateParticipantRequest, dict]): + The request object. The request message for + [Participants.CreateParticipant][google.cloud.dialogflow.v2.Participants.CreateParticipant]. + parent (:class:`str`): + Required. Resource identifier of the conversation adding + the participant. Format: + ``projects//locations//conversations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + participant (:class:`google.cloud.dialogflow_v2.types.Participant`): + Required. The participant to create. + This corresponds to the ``participant`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Participant: + Represents a conversation participant + (human agent, virtual agent, end-user). + + """ + # 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, participant]) + if request is 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 = gcd_participant.CreateParticipantRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if participant is not None: + request.participant = participant + + # 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_participant, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_participant(self, + request: Union[participant.GetParticipantRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.Participant: + r"""Retrieves a conversation participant. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetParticipantRequest, dict]): + The request object. The request message for + [Participants.GetParticipant][google.cloud.dialogflow.v2.Participants.GetParticipant]. + name (:class:`str`): + Required. The name of the participant. Format: + ``projects//locations//conversations//participants/``. + + 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.dialogflow_v2.types.Participant: + Represents a conversation participant + (human agent, virtual agent, end-user). + + """ + # 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 = participant.GetParticipantRequest(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_participant, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_participants(self, + request: Union[participant.ListParticipantsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListParticipantsAsyncPager: + r"""Returns the list of all participants in the specified + conversation. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListParticipantsRequest, dict]): + The request object. The request message for + [Participants.ListParticipants][google.cloud.dialogflow.v2.Participants.ListParticipants]. + parent (:class:`str`): + Required. The conversation to list all participants + from. Format: + ``projects//locations//conversations/``. + + 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.dialogflow_v2.services.participants.pagers.ListParticipantsAsyncPager: + The response message for + [Participants.ListParticipants][google.cloud.dialogflow.v2.Participants.ListParticipants]. + + 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 = participant.ListParticipantsRequest(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_participants, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListParticipantsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_participant(self, + request: Union[gcd_participant.UpdateParticipantRequest, dict] = None, + *, + participant: gcd_participant.Participant = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_participant.Participant: + r"""Updates the specified participant. + + Args: + request (Union[google.cloud.dialogflow_v2.types.UpdateParticipantRequest, dict]): + The request object. The request message for + [Participants.UpdateParticipant][google.cloud.dialogflow.v2.Participants.UpdateParticipant]. + participant (:class:`google.cloud.dialogflow_v2.types.Participant`): + Required. The participant to update. + This corresponds to the ``participant`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The mask to specify which + fields to update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Participant: + Represents a conversation participant + (human agent, virtual agent, end-user). + + """ + # 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([participant, 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 = gcd_participant.UpdateParticipantRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if participant is not None: + request.participant = participant + 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_participant, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("participant.name", request.participant.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def analyze_content(self, + request: Union[gcd_participant.AnalyzeContentRequest, dict] = None, + *, + participant: str = None, + text_input: session.TextInput = None, + event_input: session.EventInput = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_participant.AnalyzeContentResponse: + r"""Adds a text (chat, for example), or audio (phone recording, for + example) message from a participant into the conversation. + + Note: Always use agent versions for production traffic sent to + virtual agents. See `Versions and + environments `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.AnalyzeContentRequest, dict]): + The request object. The request message for + [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]. + participant (:class:`str`): + Required. The name of the participant this text comes + from. Format: + ``projects//locations//conversations//participants/``. + + This corresponds to the ``participant`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + text_input (:class:`google.cloud.dialogflow_v2.types.TextInput`): + The natural language text to be + processed. + + This corresponds to the ``text_input`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + event_input (:class:`google.cloud.dialogflow_v2.types.EventInput`): + An input event to send to Dialogflow. + This corresponds to the ``event_input`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.AnalyzeContentResponse: + The response message for + [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]. + + """ + # 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([participant, text_input, event_input]) + if request is 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 = gcd_participant.AnalyzeContentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if participant is not None: + request.participant = participant + if text_input is not None: + request.text_input = text_input + if event_input is not None: + request.event_input = event_input + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.analyze_content, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=220.0, + ), + default_timeout=220.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(( + ("participant", request.participant), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def suggest_articles(self, + request: Union[participant.SuggestArticlesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.SuggestArticlesResponse: + r"""Gets suggested articles for a participant based on + specific historical messages. + + Args: + request (Union[google.cloud.dialogflow_v2.types.SuggestArticlesRequest, dict]): + The request object. The request message for + [Participants.SuggestArticles][google.cloud.dialogflow.v2.Participants.SuggestArticles]. + parent (:class:`str`): + Required. The name of the participant to fetch + suggestion for. Format: + ``projects//locations//conversations//participants/``. + + 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.dialogflow_v2.types.SuggestArticlesResponse: + The response message for + [Participants.SuggestArticles][google.cloud.dialogflow.v2.Participants.SuggestArticles]. + + """ + # 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 = participant.SuggestArticlesRequest(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.suggest_articles, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def suggest_faq_answers(self, + request: Union[participant.SuggestFaqAnswersRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.SuggestFaqAnswersResponse: + r"""Gets suggested faq answers for a participant based on + specific historical messages. + + Args: + request (Union[google.cloud.dialogflow_v2.types.SuggestFaqAnswersRequest, dict]): + The request object. The request message for + [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2.Participants.SuggestFaqAnswers]. + parent (:class:`str`): + Required. The name of the participant to fetch + suggestion for. Format: + ``projects//locations//conversations//participants/``. + + 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.dialogflow_v2.types.SuggestFaqAnswersResponse: + The request message for + [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2.Participants.SuggestFaqAnswers]. + + """ + # 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 = participant.SuggestFaqAnswersRequest(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.suggest_faq_answers, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ParticipantsAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/client.py new file mode 100644 index 000000000..ad2d745ba --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/client.py @@ -0,0 +1,1001 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2.services.participants import pagers +from google.cloud.dialogflow_v2.types import participant +from google.cloud.dialogflow_v2.types import participant as gcd_participant +from google.cloud.dialogflow_v2.types import session +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ParticipantsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ParticipantsGrpcTransport +from .transports.grpc_asyncio import ParticipantsGrpcAsyncIOTransport + + +class ParticipantsClientMeta(type): + """Metaclass for the Participants 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[ParticipantsTransport]] + _transport_registry["grpc"] = ParticipantsGrpcTransport + _transport_registry["grpc_asyncio"] = ParticipantsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ParticipantsTransport]: + """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 ParticipantsClient(metaclass=ParticipantsClientMeta): + """Service for managing + [Participants][google.cloud.dialogflow.v2.Participant]. + """ + + @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 = "dialogflow.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: + ParticipantsClient: 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: + ParticipantsClient: 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) -> ParticipantsTransport: + """Returns the transport used by the client instance. + + Returns: + ParticipantsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def context_path(project: str,session: str,context: str,) -> str: + """Returns a fully-qualified context string.""" + return "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) + + @staticmethod + def parse_context_path(path: str) -> Dict[str,str]: + """Parses a context path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/contexts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def intent_path(project: str,intent: str,) -> str: + """Returns a fully-qualified intent string.""" + return "projects/{project}/agent/intents/{intent}".format(project=project, intent=intent, ) + + @staticmethod + def parse_intent_path(path: str) -> Dict[str,str]: + """Parses a intent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/intents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def message_path(project: str,conversation: str,message: str,) -> str: + """Returns a fully-qualified message string.""" + return "projects/{project}/conversations/{conversation}/messages/{message}".format(project=project, conversation=conversation, message=message, ) + + @staticmethod + def parse_message_path(path: str) -> Dict[str,str]: + """Parses a message path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/conversations/(?P.+?)/messages/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def participant_path(project: str,conversation: str,participant: str,) -> str: + """Returns a fully-qualified participant string.""" + return "projects/{project}/conversations/{conversation}/participants/{participant}".format(project=project, conversation=conversation, participant=participant, ) + + @staticmethod + def parse_participant_path(path: str) -> Dict[str,str]: + """Parses a participant path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/conversations/(?P.+?)/participants/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def session_entity_type_path(project: str,session: str,entity_type: str,) -> str: + """Returns a fully-qualified session_entity_type string.""" + return "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format(project=project, session=session, entity_type=entity_type, ) + + @staticmethod + def parse_session_entity_type_path(path: str) -> Dict[str,str]: + """Parses a session_entity_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/entityTypes/(?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, ParticipantsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the participants 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, ParticipantsTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, ParticipantsTransport): + # transport is a ParticipantsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def create_participant(self, + request: Union[gcd_participant.CreateParticipantRequest, dict] = None, + *, + parent: str = None, + participant: gcd_participant.Participant = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_participant.Participant: + r"""Creates a new participant in a conversation. + + Args: + request (Union[google.cloud.dialogflow_v2.types.CreateParticipantRequest, dict]): + The request object. The request message for + [Participants.CreateParticipant][google.cloud.dialogflow.v2.Participants.CreateParticipant]. + parent (str): + Required. Resource identifier of the conversation adding + the participant. Format: + ``projects//locations//conversations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + participant (google.cloud.dialogflow_v2.types.Participant): + Required. The participant to create. + This corresponds to the ``participant`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Participant: + Represents a conversation participant + (human agent, virtual agent, end-user). + + """ + # 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, participant]) + if request is 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 gcd_participant.CreateParticipantRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_participant.CreateParticipantRequest): + request = gcd_participant.CreateParticipantRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if participant is not None: + request.participant = participant + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_participant] + + # Certain 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_participant(self, + request: Union[participant.GetParticipantRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.Participant: + r"""Retrieves a conversation participant. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetParticipantRequest, dict]): + The request object. The request message for + [Participants.GetParticipant][google.cloud.dialogflow.v2.Participants.GetParticipant]. + name (str): + Required. The name of the participant. Format: + ``projects//locations//conversations//participants/``. + + 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.dialogflow_v2.types.Participant: + Represents a conversation participant + (human agent, virtual agent, end-user). + + """ + # 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 participant.GetParticipantRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, participant.GetParticipantRequest): + request = participant.GetParticipantRequest(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_participant] + + # Certain 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_participants(self, + request: Union[participant.ListParticipantsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListParticipantsPager: + r"""Returns the list of all participants in the specified + conversation. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListParticipantsRequest, dict]): + The request object. The request message for + [Participants.ListParticipants][google.cloud.dialogflow.v2.Participants.ListParticipants]. + parent (str): + Required. The conversation to list all participants + from. Format: + ``projects//locations//conversations/``. + + 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.dialogflow_v2.services.participants.pagers.ListParticipantsPager: + The response message for + [Participants.ListParticipants][google.cloud.dialogflow.v2.Participants.ListParticipants]. + + 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 participant.ListParticipantsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, participant.ListParticipantsRequest): + request = participant.ListParticipantsRequest(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_participants] + + # Certain 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.ListParticipantsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_participant(self, + request: Union[gcd_participant.UpdateParticipantRequest, dict] = None, + *, + participant: gcd_participant.Participant = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_participant.Participant: + r"""Updates the specified participant. + + Args: + request (Union[google.cloud.dialogflow_v2.types.UpdateParticipantRequest, dict]): + The request object. The request message for + [Participants.UpdateParticipant][google.cloud.dialogflow.v2.Participants.UpdateParticipant]. + participant (google.cloud.dialogflow_v2.types.Participant): + Required. The participant to update. + This corresponds to the ``participant`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to specify which + fields to update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Participant: + Represents a conversation participant + (human agent, virtual agent, end-user). + + """ + # 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([participant, 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 gcd_participant.UpdateParticipantRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_participant.UpdateParticipantRequest): + request = gcd_participant.UpdateParticipantRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if participant is not None: + request.participant = participant + 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_participant] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("participant.name", request.participant.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def analyze_content(self, + request: Union[gcd_participant.AnalyzeContentRequest, dict] = None, + *, + participant: str = None, + text_input: session.TextInput = None, + event_input: session.EventInput = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_participant.AnalyzeContentResponse: + r"""Adds a text (chat, for example), or audio (phone recording, for + example) message from a participant into the conversation. + + Note: Always use agent versions for production traffic sent to + virtual agents. See `Versions and + environments `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.AnalyzeContentRequest, dict]): + The request object. The request message for + [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]. + participant (str): + Required. The name of the participant this text comes + from. Format: + ``projects//locations//conversations//participants/``. + + This corresponds to the ``participant`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + text_input (google.cloud.dialogflow_v2.types.TextInput): + The natural language text to be + processed. + + This corresponds to the ``text_input`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + event_input (google.cloud.dialogflow_v2.types.EventInput): + An input event to send to Dialogflow. + This corresponds to the ``event_input`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.AnalyzeContentResponse: + The response message for + [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]. + + """ + # 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([participant, text_input, event_input]) + if request is 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 gcd_participant.AnalyzeContentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_participant.AnalyzeContentRequest): + request = gcd_participant.AnalyzeContentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if participant is not None: + request.participant = participant + if text_input is not None: + request.text_input = text_input + if event_input is not None: + request.event_input = event_input + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.analyze_content] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("participant", request.participant), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def suggest_articles(self, + request: Union[participant.SuggestArticlesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.SuggestArticlesResponse: + r"""Gets suggested articles for a participant based on + specific historical messages. + + Args: + request (Union[google.cloud.dialogflow_v2.types.SuggestArticlesRequest, dict]): + The request object. The request message for + [Participants.SuggestArticles][google.cloud.dialogflow.v2.Participants.SuggestArticles]. + parent (str): + Required. The name of the participant to fetch + suggestion for. Format: + ``projects//locations//conversations//participants/``. + + 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.dialogflow_v2.types.SuggestArticlesResponse: + The response message for + [Participants.SuggestArticles][google.cloud.dialogflow.v2.Participants.SuggestArticles]. + + """ + # 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 participant.SuggestArticlesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, participant.SuggestArticlesRequest): + request = participant.SuggestArticlesRequest(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.suggest_articles] + + # Certain 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 suggest_faq_answers(self, + request: Union[participant.SuggestFaqAnswersRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.SuggestFaqAnswersResponse: + r"""Gets suggested faq answers for a participant based on + specific historical messages. + + Args: + request (Union[google.cloud.dialogflow_v2.types.SuggestFaqAnswersRequest, dict]): + The request object. The request message for + [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2.Participants.SuggestFaqAnswers]. + parent (str): + Required. The name of the participant to fetch + suggestion for. Format: + ``projects//locations//conversations//participants/``. + + 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.dialogflow_v2.types.SuggestFaqAnswersResponse: + The request message for + [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2.Participants.SuggestFaqAnswers]. + + """ + # 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 participant.SuggestFaqAnswersRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, participant.SuggestFaqAnswersRequest): + request = participant.SuggestFaqAnswersRequest(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.suggest_faq_answers] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ParticipantsClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/pagers.py new file mode 100644 index 000000000..b4b7bfa03 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflow_v2.types import participant + + +class ListParticipantsPager: + """A pager for iterating through ``list_participants`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListParticipantsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``participants`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListParticipants`` requests and continue to iterate + through the ``participants`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListParticipantsResponse` + 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[..., participant.ListParticipantsResponse], + request: participant.ListParticipantsRequest, + response: participant.ListParticipantsResponse, + *, + 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.dialogflow_v2.types.ListParticipantsRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListParticipantsResponse): + 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 = participant.ListParticipantsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[participant.ListParticipantsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[participant.Participant]: + for page in self.pages: + yield from page.participants + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListParticipantsAsyncPager: + """A pager for iterating through ``list_participants`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListParticipantsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``participants`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListParticipants`` requests and continue to iterate + through the ``participants`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListParticipantsResponse` + 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[participant.ListParticipantsResponse]], + request: participant.ListParticipantsRequest, + response: participant.ListParticipantsResponse, + *, + 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.dialogflow_v2.types.ListParticipantsRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListParticipantsResponse): + 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 = participant.ListParticipantsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[participant.ListParticipantsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[participant.Participant]: + async def async_generator(): + async for page in self.pages: + for response in page.participants: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/__init__.py new file mode 100644 index 000000000..e30c79b00 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/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 ParticipantsTransport +from .grpc import ParticipantsGrpcTransport +from .grpc_asyncio import ParticipantsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ParticipantsTransport]] +_transport_registry['grpc'] = ParticipantsGrpcTransport +_transport_registry['grpc_asyncio'] = ParticipantsGrpcAsyncIOTransport + +__all__ = ( + 'ParticipantsTransport', + 'ParticipantsGrpcTransport', + 'ParticipantsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/base.py new file mode 100644 index 000000000..441ad3a1a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/base.py @@ -0,0 +1,238 @@ +# -*- 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.types import participant +from google.cloud.dialogflow_v2.types import participant as gcd_participant + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ParticipantsTransport(abc.ABC): + """Abstract transport class for Participants.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_participant: gapic_v1.method.wrap_method( + self.create_participant, + default_timeout=None, + client_info=client_info, + ), + self.get_participant: gapic_v1.method.wrap_method( + self.get_participant, + default_timeout=None, + client_info=client_info, + ), + self.list_participants: gapic_v1.method.wrap_method( + self.list_participants, + default_timeout=None, + client_info=client_info, + ), + self.update_participant: gapic_v1.method.wrap_method( + self.update_participant, + default_timeout=None, + client_info=client_info, + ), + self.analyze_content: gapic_v1.method.wrap_method( + self.analyze_content, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=220.0, + ), + default_timeout=220.0, + client_info=client_info, + ), + self.suggest_articles: gapic_v1.method.wrap_method( + self.suggest_articles, + default_timeout=None, + client_info=client_info, + ), + self.suggest_faq_answers: gapic_v1.method.wrap_method( + self.suggest_faq_answers, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_participant(self) -> Callable[ + [gcd_participant.CreateParticipantRequest], + Union[ + gcd_participant.Participant, + Awaitable[gcd_participant.Participant] + ]]: + raise NotImplementedError() + + @property + def get_participant(self) -> Callable[ + [participant.GetParticipantRequest], + Union[ + participant.Participant, + Awaitable[participant.Participant] + ]]: + raise NotImplementedError() + + @property + def list_participants(self) -> Callable[ + [participant.ListParticipantsRequest], + Union[ + participant.ListParticipantsResponse, + Awaitable[participant.ListParticipantsResponse] + ]]: + raise NotImplementedError() + + @property + def update_participant(self) -> Callable[ + [gcd_participant.UpdateParticipantRequest], + Union[ + gcd_participant.Participant, + Awaitable[gcd_participant.Participant] + ]]: + raise NotImplementedError() + + @property + def analyze_content(self) -> Callable[ + [gcd_participant.AnalyzeContentRequest], + Union[ + gcd_participant.AnalyzeContentResponse, + Awaitable[gcd_participant.AnalyzeContentResponse] + ]]: + raise NotImplementedError() + + @property + def suggest_articles(self) -> Callable[ + [participant.SuggestArticlesRequest], + Union[ + participant.SuggestArticlesResponse, + Awaitable[participant.SuggestArticlesResponse] + ]]: + raise NotImplementedError() + + @property + def suggest_faq_answers(self) -> Callable[ + [participant.SuggestFaqAnswersRequest], + Union[ + participant.SuggestFaqAnswersResponse, + Awaitable[participant.SuggestFaqAnswersResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'ParticipantsTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/grpc.py new file mode 100644 index 000000000..6053a4c4b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/grpc.py @@ -0,0 +1,420 @@ +# -*- 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 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import participant +from google.cloud.dialogflow_v2.types import participant as gcd_participant +from .base import ParticipantsTransport, DEFAULT_CLIENT_INFO + + +class ParticipantsGrpcTransport(ParticipantsTransport): + """gRPC backend transport for Participants. + + Service for managing + [Participants][google.cloud.dialogflow.v2.Participant]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 = 'dialogflow.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_participant(self) -> Callable[ + [gcd_participant.CreateParticipantRequest], + gcd_participant.Participant]: + r"""Return a callable for the create participant method over gRPC. + + Creates a new participant in a conversation. + + Returns: + Callable[[~.CreateParticipantRequest], + ~.Participant]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_participant' not in self._stubs: + self._stubs['create_participant'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Participants/CreateParticipant', + request_serializer=gcd_participant.CreateParticipantRequest.serialize, + response_deserializer=gcd_participant.Participant.deserialize, + ) + return self._stubs['create_participant'] + + @property + def get_participant(self) -> Callable[ + [participant.GetParticipantRequest], + participant.Participant]: + r"""Return a callable for the get participant method over gRPC. + + Retrieves a conversation participant. + + Returns: + Callable[[~.GetParticipantRequest], + ~.Participant]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_participant' not in self._stubs: + self._stubs['get_participant'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Participants/GetParticipant', + request_serializer=participant.GetParticipantRequest.serialize, + response_deserializer=participant.Participant.deserialize, + ) + return self._stubs['get_participant'] + + @property + def list_participants(self) -> Callable[ + [participant.ListParticipantsRequest], + participant.ListParticipantsResponse]: + r"""Return a callable for the list participants method over gRPC. + + Returns the list of all participants in the specified + conversation. + + Returns: + Callable[[~.ListParticipantsRequest], + ~.ListParticipantsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_participants' not in self._stubs: + self._stubs['list_participants'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Participants/ListParticipants', + request_serializer=participant.ListParticipantsRequest.serialize, + response_deserializer=participant.ListParticipantsResponse.deserialize, + ) + return self._stubs['list_participants'] + + @property + def update_participant(self) -> Callable[ + [gcd_participant.UpdateParticipantRequest], + gcd_participant.Participant]: + r"""Return a callable for the update participant method over gRPC. + + Updates the specified participant. + + Returns: + Callable[[~.UpdateParticipantRequest], + ~.Participant]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_participant' not in self._stubs: + self._stubs['update_participant'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Participants/UpdateParticipant', + request_serializer=gcd_participant.UpdateParticipantRequest.serialize, + response_deserializer=gcd_participant.Participant.deserialize, + ) + return self._stubs['update_participant'] + + @property + def analyze_content(self) -> Callable[ + [gcd_participant.AnalyzeContentRequest], + gcd_participant.AnalyzeContentResponse]: + r"""Return a callable for the analyze content method over gRPC. + + Adds a text (chat, for example), or audio (phone recording, for + example) message from a participant into the conversation. + + Note: Always use agent versions for production traffic sent to + virtual agents. See `Versions and + environments `__. + + Returns: + Callable[[~.AnalyzeContentRequest], + ~.AnalyzeContentResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'analyze_content' not in self._stubs: + self._stubs['analyze_content'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Participants/AnalyzeContent', + request_serializer=gcd_participant.AnalyzeContentRequest.serialize, + response_deserializer=gcd_participant.AnalyzeContentResponse.deserialize, + ) + return self._stubs['analyze_content'] + + @property + def suggest_articles(self) -> Callable[ + [participant.SuggestArticlesRequest], + participant.SuggestArticlesResponse]: + r"""Return a callable for the suggest articles method over gRPC. + + Gets suggested articles for a participant based on + specific historical messages. + + Returns: + Callable[[~.SuggestArticlesRequest], + ~.SuggestArticlesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'suggest_articles' not in self._stubs: + self._stubs['suggest_articles'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Participants/SuggestArticles', + request_serializer=participant.SuggestArticlesRequest.serialize, + response_deserializer=participant.SuggestArticlesResponse.deserialize, + ) + return self._stubs['suggest_articles'] + + @property + def suggest_faq_answers(self) -> Callable[ + [participant.SuggestFaqAnswersRequest], + participant.SuggestFaqAnswersResponse]: + r"""Return a callable for the suggest faq answers method over gRPC. + + Gets suggested faq answers for a participant based on + specific historical messages. + + Returns: + Callable[[~.SuggestFaqAnswersRequest], + ~.SuggestFaqAnswersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'suggest_faq_answers' not in self._stubs: + self._stubs['suggest_faq_answers'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Participants/SuggestFaqAnswers', + request_serializer=participant.SuggestFaqAnswersRequest.serialize, + response_deserializer=participant.SuggestFaqAnswersResponse.deserialize, + ) + return self._stubs['suggest_faq_answers'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'ParticipantsGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/grpc_asyncio.py new file mode 100644 index 000000000..0fc79fb0b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/grpc_asyncio.py @@ -0,0 +1,424 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import participant +from google.cloud.dialogflow_v2.types import participant as gcd_participant +from .base import ParticipantsTransport, DEFAULT_CLIENT_INFO +from .grpc import ParticipantsGrpcTransport + + +class ParticipantsGrpcAsyncIOTransport(ParticipantsTransport): + """gRPC AsyncIO backend transport for Participants. + + Service for managing + [Participants][google.cloud.dialogflow.v2.Participant]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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_participant(self) -> Callable[ + [gcd_participant.CreateParticipantRequest], + Awaitable[gcd_participant.Participant]]: + r"""Return a callable for the create participant method over gRPC. + + Creates a new participant in a conversation. + + Returns: + Callable[[~.CreateParticipantRequest], + Awaitable[~.Participant]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_participant' not in self._stubs: + self._stubs['create_participant'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Participants/CreateParticipant', + request_serializer=gcd_participant.CreateParticipantRequest.serialize, + response_deserializer=gcd_participant.Participant.deserialize, + ) + return self._stubs['create_participant'] + + @property + def get_participant(self) -> Callable[ + [participant.GetParticipantRequest], + Awaitable[participant.Participant]]: + r"""Return a callable for the get participant method over gRPC. + + Retrieves a conversation participant. + + Returns: + Callable[[~.GetParticipantRequest], + Awaitable[~.Participant]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_participant' not in self._stubs: + self._stubs['get_participant'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Participants/GetParticipant', + request_serializer=participant.GetParticipantRequest.serialize, + response_deserializer=participant.Participant.deserialize, + ) + return self._stubs['get_participant'] + + @property + def list_participants(self) -> Callable[ + [participant.ListParticipantsRequest], + Awaitable[participant.ListParticipantsResponse]]: + r"""Return a callable for the list participants method over gRPC. + + Returns the list of all participants in the specified + conversation. + + Returns: + Callable[[~.ListParticipantsRequest], + Awaitable[~.ListParticipantsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_participants' not in self._stubs: + self._stubs['list_participants'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Participants/ListParticipants', + request_serializer=participant.ListParticipantsRequest.serialize, + response_deserializer=participant.ListParticipantsResponse.deserialize, + ) + return self._stubs['list_participants'] + + @property + def update_participant(self) -> Callable[ + [gcd_participant.UpdateParticipantRequest], + Awaitable[gcd_participant.Participant]]: + r"""Return a callable for the update participant method over gRPC. + + Updates the specified participant. + + Returns: + Callable[[~.UpdateParticipantRequest], + Awaitable[~.Participant]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_participant' not in self._stubs: + self._stubs['update_participant'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Participants/UpdateParticipant', + request_serializer=gcd_participant.UpdateParticipantRequest.serialize, + response_deserializer=gcd_participant.Participant.deserialize, + ) + return self._stubs['update_participant'] + + @property + def analyze_content(self) -> Callable[ + [gcd_participant.AnalyzeContentRequest], + Awaitable[gcd_participant.AnalyzeContentResponse]]: + r"""Return a callable for the analyze content method over gRPC. + + Adds a text (chat, for example), or audio (phone recording, for + example) message from a participant into the conversation. + + Note: Always use agent versions for production traffic sent to + virtual agents. See `Versions and + environments `__. + + Returns: + Callable[[~.AnalyzeContentRequest], + Awaitable[~.AnalyzeContentResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'analyze_content' not in self._stubs: + self._stubs['analyze_content'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Participants/AnalyzeContent', + request_serializer=gcd_participant.AnalyzeContentRequest.serialize, + response_deserializer=gcd_participant.AnalyzeContentResponse.deserialize, + ) + return self._stubs['analyze_content'] + + @property + def suggest_articles(self) -> Callable[ + [participant.SuggestArticlesRequest], + Awaitable[participant.SuggestArticlesResponse]]: + r"""Return a callable for the suggest articles method over gRPC. + + Gets suggested articles for a participant based on + specific historical messages. + + Returns: + Callable[[~.SuggestArticlesRequest], + Awaitable[~.SuggestArticlesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'suggest_articles' not in self._stubs: + self._stubs['suggest_articles'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Participants/SuggestArticles', + request_serializer=participant.SuggestArticlesRequest.serialize, + response_deserializer=participant.SuggestArticlesResponse.deserialize, + ) + return self._stubs['suggest_articles'] + + @property + def suggest_faq_answers(self) -> Callable[ + [participant.SuggestFaqAnswersRequest], + Awaitable[participant.SuggestFaqAnswersResponse]]: + r"""Return a callable for the suggest faq answers method over gRPC. + + Gets suggested faq answers for a participant based on + specific historical messages. + + Returns: + Callable[[~.SuggestFaqAnswersRequest], + Awaitable[~.SuggestFaqAnswersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'suggest_faq_answers' not in self._stubs: + self._stubs['suggest_faq_answers'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Participants/SuggestFaqAnswers', + request_serializer=participant.SuggestFaqAnswersRequest.serialize, + response_deserializer=participant.SuggestFaqAnswersResponse.deserialize, + ) + return self._stubs['suggest_faq_answers'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ParticipantsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/__init__.py new file mode 100644 index 000000000..fb6678b14 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/__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 SessionEntityTypesClient +from .async_client import SessionEntityTypesAsyncClient + +__all__ = ( + 'SessionEntityTypesClient', + 'SessionEntityTypesAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/async_client.py new file mode 100644 index 000000000..c8d1616f5 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/async_client.py @@ -0,0 +1,636 @@ +# -*- 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 + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2.services.session_entity_types import pagers +from google.cloud.dialogflow_v2.types import entity_type +from google.cloud.dialogflow_v2.types import session_entity_type +from google.cloud.dialogflow_v2.types import session_entity_type as gcd_session_entity_type +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SessionEntityTypesGrpcAsyncIOTransport +from .client import SessionEntityTypesClient + + +class SessionEntityTypesAsyncClient: + """Service for managing + [SessionEntityTypes][google.cloud.dialogflow.v2.SessionEntityType]. + """ + + _client: SessionEntityTypesClient + + DEFAULT_ENDPOINT = SessionEntityTypesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SessionEntityTypesClient.DEFAULT_MTLS_ENDPOINT + + session_entity_type_path = staticmethod(SessionEntityTypesClient.session_entity_type_path) + parse_session_entity_type_path = staticmethod(SessionEntityTypesClient.parse_session_entity_type_path) + common_billing_account_path = staticmethod(SessionEntityTypesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SessionEntityTypesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SessionEntityTypesClient.common_folder_path) + parse_common_folder_path = staticmethod(SessionEntityTypesClient.parse_common_folder_path) + common_organization_path = staticmethod(SessionEntityTypesClient.common_organization_path) + parse_common_organization_path = staticmethod(SessionEntityTypesClient.parse_common_organization_path) + common_project_path = staticmethod(SessionEntityTypesClient.common_project_path) + parse_common_project_path = staticmethod(SessionEntityTypesClient.parse_common_project_path) + common_location_path = staticmethod(SessionEntityTypesClient.common_location_path) + parse_common_location_path = staticmethod(SessionEntityTypesClient.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: + SessionEntityTypesAsyncClient: The constructed client. + """ + return SessionEntityTypesClient.from_service_account_info.__func__(SessionEntityTypesAsyncClient, 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: + SessionEntityTypesAsyncClient: The constructed client. + """ + return SessionEntityTypesClient.from_service_account_file.__func__(SessionEntityTypesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SessionEntityTypesTransport: + """Returns the transport used by the client instance. + + Returns: + SessionEntityTypesTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SessionEntityTypesClient).get_transport_class, type(SessionEntityTypesClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, SessionEntityTypesTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the session entity types 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, ~.SessionEntityTypesTransport]): 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 = SessionEntityTypesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_session_entity_types(self, + request: Union[session_entity_type.ListSessionEntityTypesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSessionEntityTypesAsyncPager: + r"""Returns the list of all session entity types in the + specified session. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListSessionEntityTypesRequest, dict]): + The request object. The request message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2.SessionEntityTypes.ListSessionEntityTypes]. + parent (:class:`str`): + Required. The session to list all session entity types + from. Format: + ``projects//agent/sessions/`` or + ``projects//agent/environments//users// sessions/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. If ``User ID`` is not + specified, we assume default '-' user. + + 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.dialogflow_v2.services.session_entity_types.pagers.ListSessionEntityTypesAsyncPager: + The response message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2.SessionEntityTypes.ListSessionEntityTypes]. + + 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 = session_entity_type.ListSessionEntityTypesRequest(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_session_entity_types, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSessionEntityTypesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_session_entity_type(self, + request: Union[session_entity_type.GetSessionEntityTypeRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> session_entity_type.SessionEntityType: + r"""Retrieves the specified session entity type. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetSessionEntityTypeRequest, dict]): + The request object. The request message for + [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.GetSessionEntityType]. + name (:class:`str`): + Required. The name of the session entity type. Format: + ``projects//agent/sessions//entityTypes/`` + or + ``projects//agent/environments//users//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. If ``User ID`` is not + specified, we assume default '-' user. + + 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.dialogflow_v2.types.SessionEntityType: + A session represents a conversation between a Dialogflow agent and an + end-user. You can create special entities, called + session entities, during a session. Session entities + can extend or replace custom entity types and only + exist during the session that they were created for. + All session data, including session entities, is + stored by Dialogflow for 20 minutes. + + For more information, see the [session entity + guide](\ https://cloud.google.com/dialogflow/docs/entities-session). + + """ + # 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 = session_entity_type.GetSessionEntityTypeRequest(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_session_entity_type, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_session_entity_type(self, + request: Union[gcd_session_entity_type.CreateSessionEntityTypeRequest, dict] = None, + *, + parent: str = None, + session_entity_type: gcd_session_entity_type.SessionEntityType = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_session_entity_type.SessionEntityType: + r"""Creates a session entity type. + If the specified session entity type already exists, + overrides the session entity type. + + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Args: + request (Union[google.cloud.dialogflow_v2.types.CreateSessionEntityTypeRequest, dict]): + The request object. The request message for + [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.CreateSessionEntityType]. + parent (:class:`str`): + Required. The session to create a session entity type + for. Format: + ``projects//agent/sessions/`` or + ``projects//agent/environments//users// sessions/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. If ``User ID`` is not + specified, we assume default '-' user. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + session_entity_type (:class:`google.cloud.dialogflow_v2.types.SessionEntityType`): + Required. The session entity type to + create. + + This corresponds to the ``session_entity_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.SessionEntityType: + A session represents a conversation between a Dialogflow agent and an + end-user. You can create special entities, called + session entities, during a session. Session entities + can extend or replace custom entity types and only + exist during the session that they were created for. + All session data, including session entities, is + stored by Dialogflow for 20 minutes. + + For more information, see the [session entity + guide](\ https://cloud.google.com/dialogflow/docs/entities-session). + + """ + # 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, session_entity_type]) + if request is 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 = gcd_session_entity_type.CreateSessionEntityTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if session_entity_type is not None: + request.session_entity_type = session_entity_type + + # 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_session_entity_type, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_session_entity_type(self, + request: Union[gcd_session_entity_type.UpdateSessionEntityTypeRequest, dict] = None, + *, + session_entity_type: gcd_session_entity_type.SessionEntityType = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_session_entity_type.SessionEntityType: + r"""Updates the specified session entity type. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Args: + request (Union[google.cloud.dialogflow_v2.types.UpdateSessionEntityTypeRequest, dict]): + The request object. The request message for + [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.UpdateSessionEntityType]. + session_entity_type (:class:`google.cloud.dialogflow_v2.types.SessionEntityType`): + Required. The session entity type to + update. + + This corresponds to the ``session_entity_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.SessionEntityType: + A session represents a conversation between a Dialogflow agent and an + end-user. You can create special entities, called + session entities, during a session. Session entities + can extend or replace custom entity types and only + exist during the session that they were created for. + All session data, including session entities, is + stored by Dialogflow for 20 minutes. + + For more information, see the [session entity + guide](\ https://cloud.google.com/dialogflow/docs/entities-session). + + """ + # 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([session_entity_type, 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 = gcd_session_entity_type.UpdateSessionEntityTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if session_entity_type is not None: + request.session_entity_type = session_entity_type + 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_session_entity_type, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("session_entity_type.name", request.session_entity_type.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_session_entity_type(self, + request: Union[session_entity_type.DeleteSessionEntityTypeRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified session entity type. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Args: + request (Union[google.cloud.dialogflow_v2.types.DeleteSessionEntityTypeRequest, dict]): + The request object. The request message for + [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.DeleteSessionEntityType]. + name (:class:`str`): + Required. The name of the entity type to delete. Format: + ``projects//agent/sessions//entityTypes/`` + or + ``projects//agent/environments//users//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. If ``User ID`` is not + specified, we assume default '-' user. + + 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 = session_entity_type.DeleteSessionEntityTypeRequest(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_session_entity_type, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SessionEntityTypesAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/client.py new file mode 100644 index 000000000..4f6d3a855 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/client.py @@ -0,0 +1,834 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2.services.session_entity_types import pagers +from google.cloud.dialogflow_v2.types import entity_type +from google.cloud.dialogflow_v2.types import session_entity_type +from google.cloud.dialogflow_v2.types import session_entity_type as gcd_session_entity_type +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SessionEntityTypesGrpcTransport +from .transports.grpc_asyncio import SessionEntityTypesGrpcAsyncIOTransport + + +class SessionEntityTypesClientMeta(type): + """Metaclass for the SessionEntityTypes 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[SessionEntityTypesTransport]] + _transport_registry["grpc"] = SessionEntityTypesGrpcTransport + _transport_registry["grpc_asyncio"] = SessionEntityTypesGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[SessionEntityTypesTransport]: + """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 SessionEntityTypesClient(metaclass=SessionEntityTypesClientMeta): + """Service for managing + [SessionEntityTypes][google.cloud.dialogflow.v2.SessionEntityType]. + """ + + @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 = "dialogflow.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: + SessionEntityTypesClient: 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: + SessionEntityTypesClient: 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) -> SessionEntityTypesTransport: + """Returns the transport used by the client instance. + + Returns: + SessionEntityTypesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def session_entity_type_path(project: str,session: str,entity_type: str,) -> str: + """Returns a fully-qualified session_entity_type string.""" + return "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format(project=project, session=session, entity_type=entity_type, ) + + @staticmethod + def parse_session_entity_type_path(path: str) -> Dict[str,str]: + """Parses a session_entity_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/entityTypes/(?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, SessionEntityTypesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the session entity types 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, SessionEntityTypesTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, SessionEntityTypesTransport): + # transport is a SessionEntityTypesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_session_entity_types(self, + request: Union[session_entity_type.ListSessionEntityTypesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSessionEntityTypesPager: + r"""Returns the list of all session entity types in the + specified session. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListSessionEntityTypesRequest, dict]): + The request object. The request message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2.SessionEntityTypes.ListSessionEntityTypes]. + parent (str): + Required. The session to list all session entity types + from. Format: + ``projects//agent/sessions/`` or + ``projects//agent/environments//users// sessions/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. If ``User ID`` is not + specified, we assume default '-' user. + + 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.dialogflow_v2.services.session_entity_types.pagers.ListSessionEntityTypesPager: + The response message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2.SessionEntityTypes.ListSessionEntityTypes]. + + 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 session_entity_type.ListSessionEntityTypesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, session_entity_type.ListSessionEntityTypesRequest): + request = session_entity_type.ListSessionEntityTypesRequest(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_session_entity_types] + + # Certain 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.ListSessionEntityTypesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_session_entity_type(self, + request: Union[session_entity_type.GetSessionEntityTypeRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> session_entity_type.SessionEntityType: + r"""Retrieves the specified session entity type. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetSessionEntityTypeRequest, dict]): + The request object. The request message for + [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.GetSessionEntityType]. + name (str): + Required. The name of the session entity type. Format: + ``projects//agent/sessions//entityTypes/`` + or + ``projects//agent/environments//users//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. If ``User ID`` is not + specified, we assume default '-' user. + + 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.dialogflow_v2.types.SessionEntityType: + A session represents a conversation between a Dialogflow agent and an + end-user. You can create special entities, called + session entities, during a session. Session entities + can extend or replace custom entity types and only + exist during the session that they were created for. + All session data, including session entities, is + stored by Dialogflow for 20 minutes. + + For more information, see the [session entity + guide](\ https://cloud.google.com/dialogflow/docs/entities-session). + + """ + # 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 session_entity_type.GetSessionEntityTypeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, session_entity_type.GetSessionEntityTypeRequest): + request = session_entity_type.GetSessionEntityTypeRequest(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_session_entity_type] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_session_entity_type(self, + request: Union[gcd_session_entity_type.CreateSessionEntityTypeRequest, dict] = None, + *, + parent: str = None, + session_entity_type: gcd_session_entity_type.SessionEntityType = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_session_entity_type.SessionEntityType: + r"""Creates a session entity type. + If the specified session entity type already exists, + overrides the session entity type. + + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Args: + request (Union[google.cloud.dialogflow_v2.types.CreateSessionEntityTypeRequest, dict]): + The request object. The request message for + [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.CreateSessionEntityType]. + parent (str): + Required. The session to create a session entity type + for. Format: + ``projects//agent/sessions/`` or + ``projects//agent/environments//users// sessions/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. If ``User ID`` is not + specified, we assume default '-' user. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + session_entity_type (google.cloud.dialogflow_v2.types.SessionEntityType): + Required. The session entity type to + create. + + This corresponds to the ``session_entity_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.SessionEntityType: + A session represents a conversation between a Dialogflow agent and an + end-user. You can create special entities, called + session entities, during a session. Session entities + can extend or replace custom entity types and only + exist during the session that they were created for. + All session data, including session entities, is + stored by Dialogflow for 20 minutes. + + For more information, see the [session entity + guide](\ https://cloud.google.com/dialogflow/docs/entities-session). + + """ + # 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, session_entity_type]) + if request is 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 gcd_session_entity_type.CreateSessionEntityTypeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_session_entity_type.CreateSessionEntityTypeRequest): + request = gcd_session_entity_type.CreateSessionEntityTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if session_entity_type is not None: + request.session_entity_type = session_entity_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_session_entity_type] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_session_entity_type(self, + request: Union[gcd_session_entity_type.UpdateSessionEntityTypeRequest, dict] = None, + *, + session_entity_type: gcd_session_entity_type.SessionEntityType = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_session_entity_type.SessionEntityType: + r"""Updates the specified session entity type. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Args: + request (Union[google.cloud.dialogflow_v2.types.UpdateSessionEntityTypeRequest, dict]): + The request object. The request message for + [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.UpdateSessionEntityType]. + session_entity_type (google.cloud.dialogflow_v2.types.SessionEntityType): + Required. The session entity type to + update. + + This corresponds to the ``session_entity_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.SessionEntityType: + A session represents a conversation between a Dialogflow agent and an + end-user. You can create special entities, called + session entities, during a session. Session entities + can extend or replace custom entity types and only + exist during the session that they were created for. + All session data, including session entities, is + stored by Dialogflow for 20 minutes. + + For more information, see the [session entity + guide](\ https://cloud.google.com/dialogflow/docs/entities-session). + + """ + # 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([session_entity_type, 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 gcd_session_entity_type.UpdateSessionEntityTypeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_session_entity_type.UpdateSessionEntityTypeRequest): + request = gcd_session_entity_type.UpdateSessionEntityTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if session_entity_type is not None: + request.session_entity_type = session_entity_type + 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_session_entity_type] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("session_entity_type.name", request.session_entity_type.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_session_entity_type(self, + request: Union[session_entity_type.DeleteSessionEntityTypeRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified session entity type. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Args: + request (Union[google.cloud.dialogflow_v2.types.DeleteSessionEntityTypeRequest, dict]): + The request object. The request message for + [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.DeleteSessionEntityType]. + name (str): + Required. The name of the entity type to delete. Format: + ``projects//agent/sessions//entityTypes/`` + or + ``projects//agent/environments//users//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. If ``User ID`` is not + specified, we assume default '-' user. + + 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 session_entity_type.DeleteSessionEntityTypeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, session_entity_type.DeleteSessionEntityTypeRequest): + request = session_entity_type.DeleteSessionEntityTypeRequest(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_session_entity_type] + + # Certain 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 __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SessionEntityTypesClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/pagers.py new file mode 100644 index 000000000..39523ebb8 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflow_v2.types import session_entity_type + + +class ListSessionEntityTypesPager: + """A pager for iterating through ``list_session_entity_types`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListSessionEntityTypesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``session_entity_types`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSessionEntityTypes`` requests and continue to iterate + through the ``session_entity_types`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListSessionEntityTypesResponse` + 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[..., session_entity_type.ListSessionEntityTypesResponse], + request: session_entity_type.ListSessionEntityTypesRequest, + response: session_entity_type.ListSessionEntityTypesResponse, + *, + 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.dialogflow_v2.types.ListSessionEntityTypesRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListSessionEntityTypesResponse): + 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 = session_entity_type.ListSessionEntityTypesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[session_entity_type.ListSessionEntityTypesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[session_entity_type.SessionEntityType]: + for page in self.pages: + yield from page.session_entity_types + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSessionEntityTypesAsyncPager: + """A pager for iterating through ``list_session_entity_types`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListSessionEntityTypesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``session_entity_types`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSessionEntityTypes`` requests and continue to iterate + through the ``session_entity_types`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListSessionEntityTypesResponse` + 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[session_entity_type.ListSessionEntityTypesResponse]], + request: session_entity_type.ListSessionEntityTypesRequest, + response: session_entity_type.ListSessionEntityTypesResponse, + *, + 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.dialogflow_v2.types.ListSessionEntityTypesRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListSessionEntityTypesResponse): + 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 = session_entity_type.ListSessionEntityTypesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[session_entity_type.ListSessionEntityTypesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[session_entity_type.SessionEntityType]: + async def async_generator(): + async for page in self.pages: + for response in page.session_entity_types: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/__init__.py new file mode 100644 index 000000000..fee526724 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/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 SessionEntityTypesTransport +from .grpc import SessionEntityTypesGrpcTransport +from .grpc_asyncio import SessionEntityTypesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SessionEntityTypesTransport]] +_transport_registry['grpc'] = SessionEntityTypesGrpcTransport +_transport_registry['grpc_asyncio'] = SessionEntityTypesGrpcAsyncIOTransport + +__all__ = ( + 'SessionEntityTypesTransport', + 'SessionEntityTypesGrpcTransport', + 'SessionEntityTypesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/base.py new file mode 100644 index 000000000..5856683c0 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/base.py @@ -0,0 +1,205 @@ +# -*- 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.types import session_entity_type +from google.cloud.dialogflow_v2.types import session_entity_type as gcd_session_entity_type +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-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class SessionEntityTypesTransport(abc.ABC): + """Abstract transport class for SessionEntityTypes.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_session_entity_types: gapic_v1.method.wrap_method( + self.list_session_entity_types, + default_timeout=None, + client_info=client_info, + ), + self.get_session_entity_type: gapic_v1.method.wrap_method( + self.get_session_entity_type, + default_timeout=None, + client_info=client_info, + ), + self.create_session_entity_type: gapic_v1.method.wrap_method( + self.create_session_entity_type, + default_timeout=None, + client_info=client_info, + ), + self.update_session_entity_type: gapic_v1.method.wrap_method( + self.update_session_entity_type, + default_timeout=None, + client_info=client_info, + ), + self.delete_session_entity_type: gapic_v1.method.wrap_method( + self.delete_session_entity_type, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_session_entity_types(self) -> Callable[ + [session_entity_type.ListSessionEntityTypesRequest], + Union[ + session_entity_type.ListSessionEntityTypesResponse, + Awaitable[session_entity_type.ListSessionEntityTypesResponse] + ]]: + raise NotImplementedError() + + @property + def get_session_entity_type(self) -> Callable[ + [session_entity_type.GetSessionEntityTypeRequest], + Union[ + session_entity_type.SessionEntityType, + Awaitable[session_entity_type.SessionEntityType] + ]]: + raise NotImplementedError() + + @property + def create_session_entity_type(self) -> Callable[ + [gcd_session_entity_type.CreateSessionEntityTypeRequest], + Union[ + gcd_session_entity_type.SessionEntityType, + Awaitable[gcd_session_entity_type.SessionEntityType] + ]]: + raise NotImplementedError() + + @property + def update_session_entity_type(self) -> Callable[ + [gcd_session_entity_type.UpdateSessionEntityTypeRequest], + Union[ + gcd_session_entity_type.SessionEntityType, + Awaitable[gcd_session_entity_type.SessionEntityType] + ]]: + raise NotImplementedError() + + @property + def delete_session_entity_type(self) -> Callable[ + [session_entity_type.DeleteSessionEntityTypeRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'SessionEntityTypesTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc.py new file mode 100644 index 000000000..80f802d48 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc.py @@ -0,0 +1,380 @@ +# -*- 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 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import session_entity_type +from google.cloud.dialogflow_v2.types import session_entity_type as gcd_session_entity_type +from google.protobuf import empty_pb2 # type: ignore +from .base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO + + +class SessionEntityTypesGrpcTransport(SessionEntityTypesTransport): + """gRPC backend transport for SessionEntityTypes. + + Service for managing + [SessionEntityTypes][google.cloud.dialogflow.v2.SessionEntityType]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 = 'dialogflow.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 list_session_entity_types(self) -> Callable[ + [session_entity_type.ListSessionEntityTypesRequest], + session_entity_type.ListSessionEntityTypesResponse]: + r"""Return a callable for the list session entity types method over gRPC. + + Returns the list of all session entity types in the + specified session. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Returns: + Callable[[~.ListSessionEntityTypesRequest], + ~.ListSessionEntityTypesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_session_entity_types' not in self._stubs: + self._stubs['list_session_entity_types'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.SessionEntityTypes/ListSessionEntityTypes', + request_serializer=session_entity_type.ListSessionEntityTypesRequest.serialize, + response_deserializer=session_entity_type.ListSessionEntityTypesResponse.deserialize, + ) + return self._stubs['list_session_entity_types'] + + @property + def get_session_entity_type(self) -> Callable[ + [session_entity_type.GetSessionEntityTypeRequest], + session_entity_type.SessionEntityType]: + r"""Return a callable for the get session entity type method over gRPC. + + Retrieves the specified session entity type. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Returns: + Callable[[~.GetSessionEntityTypeRequest], + ~.SessionEntityType]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_session_entity_type' not in self._stubs: + self._stubs['get_session_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.SessionEntityTypes/GetSessionEntityType', + request_serializer=session_entity_type.GetSessionEntityTypeRequest.serialize, + response_deserializer=session_entity_type.SessionEntityType.deserialize, + ) + return self._stubs['get_session_entity_type'] + + @property + def create_session_entity_type(self) -> Callable[ + [gcd_session_entity_type.CreateSessionEntityTypeRequest], + gcd_session_entity_type.SessionEntityType]: + r"""Return a callable for the create session entity type method over gRPC. + + Creates a session entity type. + If the specified session entity type already exists, + overrides the session entity type. + + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Returns: + Callable[[~.CreateSessionEntityTypeRequest], + ~.SessionEntityType]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_session_entity_type' not in self._stubs: + self._stubs['create_session_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.SessionEntityTypes/CreateSessionEntityType', + request_serializer=gcd_session_entity_type.CreateSessionEntityTypeRequest.serialize, + response_deserializer=gcd_session_entity_type.SessionEntityType.deserialize, + ) + return self._stubs['create_session_entity_type'] + + @property + def update_session_entity_type(self) -> Callable[ + [gcd_session_entity_type.UpdateSessionEntityTypeRequest], + gcd_session_entity_type.SessionEntityType]: + r"""Return a callable for the update session entity type method over gRPC. + + Updates the specified session entity type. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Returns: + Callable[[~.UpdateSessionEntityTypeRequest], + ~.SessionEntityType]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_session_entity_type' not in self._stubs: + self._stubs['update_session_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.SessionEntityTypes/UpdateSessionEntityType', + request_serializer=gcd_session_entity_type.UpdateSessionEntityTypeRequest.serialize, + response_deserializer=gcd_session_entity_type.SessionEntityType.deserialize, + ) + return self._stubs['update_session_entity_type'] + + @property + def delete_session_entity_type(self) -> Callable[ + [session_entity_type.DeleteSessionEntityTypeRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete session entity type method over gRPC. + + Deletes the specified session entity type. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Returns: + Callable[[~.DeleteSessionEntityTypeRequest], + ~.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_session_entity_type' not in self._stubs: + self._stubs['delete_session_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.SessionEntityTypes/DeleteSessionEntityType', + request_serializer=session_entity_type.DeleteSessionEntityTypeRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_session_entity_type'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'SessionEntityTypesGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc_asyncio.py new file mode 100644 index 000000000..aebb92fd3 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc_asyncio.py @@ -0,0 +1,384 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import session_entity_type +from google.cloud.dialogflow_v2.types import session_entity_type as gcd_session_entity_type +from google.protobuf import empty_pb2 # type: ignore +from .base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO +from .grpc import SessionEntityTypesGrpcTransport + + +class SessionEntityTypesGrpcAsyncIOTransport(SessionEntityTypesTransport): + """gRPC AsyncIO backend transport for SessionEntityTypes. + + Service for managing + [SessionEntityTypes][google.cloud.dialogflow.v2.SessionEntityType]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 list_session_entity_types(self) -> Callable[ + [session_entity_type.ListSessionEntityTypesRequest], + Awaitable[session_entity_type.ListSessionEntityTypesResponse]]: + r"""Return a callable for the list session entity types method over gRPC. + + Returns the list of all session entity types in the + specified session. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Returns: + Callable[[~.ListSessionEntityTypesRequest], + Awaitable[~.ListSessionEntityTypesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_session_entity_types' not in self._stubs: + self._stubs['list_session_entity_types'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.SessionEntityTypes/ListSessionEntityTypes', + request_serializer=session_entity_type.ListSessionEntityTypesRequest.serialize, + response_deserializer=session_entity_type.ListSessionEntityTypesResponse.deserialize, + ) + return self._stubs['list_session_entity_types'] + + @property + def get_session_entity_type(self) -> Callable[ + [session_entity_type.GetSessionEntityTypeRequest], + Awaitable[session_entity_type.SessionEntityType]]: + r"""Return a callable for the get session entity type method over gRPC. + + Retrieves the specified session entity type. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Returns: + Callable[[~.GetSessionEntityTypeRequest], + Awaitable[~.SessionEntityType]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_session_entity_type' not in self._stubs: + self._stubs['get_session_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.SessionEntityTypes/GetSessionEntityType', + request_serializer=session_entity_type.GetSessionEntityTypeRequest.serialize, + response_deserializer=session_entity_type.SessionEntityType.deserialize, + ) + return self._stubs['get_session_entity_type'] + + @property + def create_session_entity_type(self) -> Callable[ + [gcd_session_entity_type.CreateSessionEntityTypeRequest], + Awaitable[gcd_session_entity_type.SessionEntityType]]: + r"""Return a callable for the create session entity type method over gRPC. + + Creates a session entity type. + If the specified session entity type already exists, + overrides the session entity type. + + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Returns: + Callable[[~.CreateSessionEntityTypeRequest], + Awaitable[~.SessionEntityType]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_session_entity_type' not in self._stubs: + self._stubs['create_session_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.SessionEntityTypes/CreateSessionEntityType', + request_serializer=gcd_session_entity_type.CreateSessionEntityTypeRequest.serialize, + response_deserializer=gcd_session_entity_type.SessionEntityType.deserialize, + ) + return self._stubs['create_session_entity_type'] + + @property + def update_session_entity_type(self) -> Callable[ + [gcd_session_entity_type.UpdateSessionEntityTypeRequest], + Awaitable[gcd_session_entity_type.SessionEntityType]]: + r"""Return a callable for the update session entity type method over gRPC. + + Updates the specified session entity type. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Returns: + Callable[[~.UpdateSessionEntityTypeRequest], + Awaitable[~.SessionEntityType]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_session_entity_type' not in self._stubs: + self._stubs['update_session_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.SessionEntityTypes/UpdateSessionEntityType', + request_serializer=gcd_session_entity_type.UpdateSessionEntityTypeRequest.serialize, + response_deserializer=gcd_session_entity_type.SessionEntityType.deserialize, + ) + return self._stubs['update_session_entity_type'] + + @property + def delete_session_entity_type(self) -> Callable[ + [session_entity_type.DeleteSessionEntityTypeRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete session entity type method over gRPC. + + Deletes the specified session entity type. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Returns: + Callable[[~.DeleteSessionEntityTypeRequest], + 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_session_entity_type' not in self._stubs: + self._stubs['delete_session_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.SessionEntityTypes/DeleteSessionEntityType', + request_serializer=session_entity_type.DeleteSessionEntityTypeRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_session_entity_type'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'SessionEntityTypesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/__init__.py new file mode 100644 index 000000000..92490cc5a --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/__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 SessionsClient +from .async_client import SessionsAsyncClient + +__all__ = ( + 'SessionsClient', + 'SessionsAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/async_client.py new file mode 100644 index 000000000..08ad284ff --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/async_client.py @@ -0,0 +1,419 @@ +# -*- 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, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2.types import audio_config +from google.cloud.dialogflow_v2.types import session +from google.cloud.dialogflow_v2.types import session as gcd_session +from google.rpc import status_pb2 # type: ignore +from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport +from .client import SessionsClient + + +class SessionsAsyncClient: + """A service used for session interactions. + + For more information, see the `API interactions + guide `__. + """ + + _client: SessionsClient + + DEFAULT_ENDPOINT = SessionsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SessionsClient.DEFAULT_MTLS_ENDPOINT + + context_path = staticmethod(SessionsClient.context_path) + parse_context_path = staticmethod(SessionsClient.parse_context_path) + intent_path = staticmethod(SessionsClient.intent_path) + parse_intent_path = staticmethod(SessionsClient.parse_intent_path) + session_path = staticmethod(SessionsClient.session_path) + parse_session_path = staticmethod(SessionsClient.parse_session_path) + session_entity_type_path = staticmethod(SessionsClient.session_entity_type_path) + parse_session_entity_type_path = staticmethod(SessionsClient.parse_session_entity_type_path) + common_billing_account_path = staticmethod(SessionsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SessionsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SessionsClient.common_folder_path) + parse_common_folder_path = staticmethod(SessionsClient.parse_common_folder_path) + common_organization_path = staticmethod(SessionsClient.common_organization_path) + parse_common_organization_path = staticmethod(SessionsClient.parse_common_organization_path) + common_project_path = staticmethod(SessionsClient.common_project_path) + parse_common_project_path = staticmethod(SessionsClient.parse_common_project_path) + common_location_path = staticmethod(SessionsClient.common_location_path) + parse_common_location_path = staticmethod(SessionsClient.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: + SessionsAsyncClient: The constructed client. + """ + return SessionsClient.from_service_account_info.__func__(SessionsAsyncClient, 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: + SessionsAsyncClient: The constructed client. + """ + return SessionsClient.from_service_account_file.__func__(SessionsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SessionsTransport: + """Returns the transport used by the client instance. + + Returns: + SessionsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SessionsClient).get_transport_class, type(SessionsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, SessionsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the sessions 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, ~.SessionsTransport]): 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 = SessionsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def detect_intent(self, + request: Union[gcd_session.DetectIntentRequest, dict] = None, + *, + session: str = None, + query_input: gcd_session.QueryInput = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_session.DetectIntentResponse: + r"""Processes a natural language query and returns structured, + actionable data as a result. This method is not idempotent, + because it may cause contexts and session entity types to be + updated, which in turn might affect results of future queries. + + If you might use `Agent + Assist `__ or + other CCAI products now or in the future, consider using + [AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent] + instead of ``DetectIntent``. ``AnalyzeContent`` has additional + functionality for Agent Assist and other CCAI products. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.DetectIntentRequest, dict]): + The request object. The request to detect user's intent. + session (:class:`str`): + Required. The name of the session this query is sent to. + Format: + ``projects//agent/sessions/``, + or + ``projects//agent/environments//users//sessions/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment (``Environment ID`` might be + referred to as environment name at some places). If + ``User ID`` is not specified, we are using "-". It's up + to the API caller to choose an appropriate + ``Session ID`` and ``User Id``. They can be a random + number or some type of user and session identifiers + (preferably hashed). The length of the ``Session ID`` + and ``User ID`` must not exceed 36 characters. + + For more information, see the `API interactions + guide `__. + + Note: Always use agent versions for production traffic. + See `Versions and + environments `__. + + This corresponds to the ``session`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query_input (:class:`google.cloud.dialogflow_v2.types.QueryInput`): + Required. The input specification. It + can be set to: + 1. an audio config + which instructs the speech + recognizer how to process the speech + audio, + 2. a conversational query in the form + of text, or + 3. an event that specifies which intent + to trigger. + + This corresponds to the ``query_input`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.DetectIntentResponse: + The message returned from the + DetectIntent method. + + """ + # 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([session, query_input]) + if request is 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 = gcd_session.DetectIntentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if session is not None: + request.session = session + if query_input is not None: + request.query_input = query_input + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.detect_intent, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=220.0, + ), + default_timeout=220.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(( + ("session", request.session), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def streaming_detect_intent(self, + requests: AsyncIterator[session.StreamingDetectIntentRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Awaitable[AsyncIterable[session.StreamingDetectIntentResponse]]: + r"""Processes a natural language query in audio format in a + streaming fashion and returns structured, actionable data as a + result. This method is only available via the gRPC API (not + REST). + + If you might use `Agent + Assist `__ or + other CCAI products now or in the future, consider using + [StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent] + instead of ``StreamingDetectIntent``. + ``StreamingAnalyzeContent`` has additional functionality for + Agent Assist and other CCAI products. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Args: + requests (AsyncIterator[`google.cloud.dialogflow_v2.types.StreamingDetectIntentRequest`]): + The request object AsyncIterator. The top-level message sent by the + client to the + [Sessions.StreamingDetectIntent][google.cloud.dialogflow.v2.Sessions.StreamingDetectIntent] + method. + Multiple request messages should be sent in order: + + 1. The first message must contain + [session][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.session], + [query_input][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_input] + plus optionally + [query_params][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_params]. + If the client wants to receive an audio response, it + should also contain + [output_audio_config][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.output_audio_config]. + The message must not contain + [input_audio][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.input_audio]. + 2. If + [query_input][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_input] + was set to + [query_input.audio_config][google.cloud.dialogflow.v2.InputAudioConfig], + all subsequent messages must contain + [input_audio][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.input_audio] + to continue with Speech recognition. + If you decide to rather detect an intent from text + input after you already started Speech recognition, + please send a message with + [query_input.text][google.cloud.dialogflow.v2.QueryInput.text]. + However, note that: + + * Dialogflow will bill you for the audio duration so + far. * Dialogflow discards all Speech recognition + results in favor of the input text. + * Dialogflow will use the language code from the + first message. + After you sent all input, you must half-close or abort + the request stream. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + AsyncIterable[google.cloud.dialogflow_v2.types.StreamingDetectIntentResponse]: + The top-level message returned from the + StreamingDetectIntent method. + + Multiple response messages can be returned in order: + + 1. If the StreamingDetectIntentRequest.input_audio + field was set, the recognition_result field is + populated for one or more messages. See the + [StreamingRecognitionResult][google.cloud.dialogflow.v2.StreamingRecognitionResult] + message for details about the result message + sequence. + 2. The next message contains response_id, + query_result and optionally webhook_status if a + WebHook was called. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.streaming_detect_intent, + default_timeout=220.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SessionsAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/client.py new file mode 100644 index 000000000..020cb6d73 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/client.py @@ -0,0 +1,634 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2.types import audio_config +from google.cloud.dialogflow_v2.types import session +from google.cloud.dialogflow_v2.types import session as gcd_session +from google.rpc import status_pb2 # type: ignore +from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SessionsGrpcTransport +from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport + + +class SessionsClientMeta(type): + """Metaclass for the Sessions 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[SessionsTransport]] + _transport_registry["grpc"] = SessionsGrpcTransport + _transport_registry["grpc_asyncio"] = SessionsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[SessionsTransport]: + """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 SessionsClient(metaclass=SessionsClientMeta): + """A service used for session interactions. + + For more information, see the `API interactions + guide `__. + """ + + @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 = "dialogflow.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: + SessionsClient: 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: + SessionsClient: 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) -> SessionsTransport: + """Returns the transport used by the client instance. + + Returns: + SessionsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def context_path(project: str,session: str,context: str,) -> str: + """Returns a fully-qualified context string.""" + return "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) + + @staticmethod + def parse_context_path(path: str) -> Dict[str,str]: + """Parses a context path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/contexts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def intent_path(project: str,intent: str,) -> str: + """Returns a fully-qualified intent string.""" + return "projects/{project}/agent/intents/{intent}".format(project=project, intent=intent, ) + + @staticmethod + def parse_intent_path(path: str) -> Dict[str,str]: + """Parses a intent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/intents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def session_path(project: str,session: str,) -> str: + """Returns a fully-qualified session string.""" + return "projects/{project}/agent/sessions/{session}".format(project=project, session=session, ) + + @staticmethod + def parse_session_path(path: str) -> Dict[str,str]: + """Parses a session path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def session_entity_type_path(project: str,session: str,entity_type: str,) -> str: + """Returns a fully-qualified session_entity_type string.""" + return "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format(project=project, session=session, entity_type=entity_type, ) + + @staticmethod + def parse_session_entity_type_path(path: str) -> Dict[str,str]: + """Parses a session_entity_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/entityTypes/(?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, SessionsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the sessions 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, SessionsTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, SessionsTransport): + # transport is a SessionsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def detect_intent(self, + request: Union[gcd_session.DetectIntentRequest, dict] = None, + *, + session: str = None, + query_input: gcd_session.QueryInput = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_session.DetectIntentResponse: + r"""Processes a natural language query and returns structured, + actionable data as a result. This method is not idempotent, + because it may cause contexts and session entity types to be + updated, which in turn might affect results of future queries. + + If you might use `Agent + Assist `__ or + other CCAI products now or in the future, consider using + [AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent] + instead of ``DetectIntent``. ``AnalyzeContent`` has additional + functionality for Agent Assist and other CCAI products. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Args: + request (Union[google.cloud.dialogflow_v2.types.DetectIntentRequest, dict]): + The request object. The request to detect user's intent. + session (str): + Required. The name of the session this query is sent to. + Format: + ``projects//agent/sessions/``, + or + ``projects//agent/environments//users//sessions/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment (``Environment ID`` might be + referred to as environment name at some places). If + ``User ID`` is not specified, we are using "-". It's up + to the API caller to choose an appropriate + ``Session ID`` and ``User Id``. They can be a random + number or some type of user and session identifiers + (preferably hashed). The length of the ``Session ID`` + and ``User ID`` must not exceed 36 characters. + + For more information, see the `API interactions + guide `__. + + Note: Always use agent versions for production traffic. + See `Versions and + environments `__. + + This corresponds to the ``session`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query_input (google.cloud.dialogflow_v2.types.QueryInput): + Required. The input specification. It + can be set to: + 1. an audio config + which instructs the speech + recognizer how to process the speech + audio, + 2. a conversational query in the form + of text, or + 3. an event that specifies which intent + to trigger. + + This corresponds to the ``query_input`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.DetectIntentResponse: + The message returned from the + DetectIntent method. + + """ + # 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([session, query_input]) + if request is 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 gcd_session.DetectIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_session.DetectIntentRequest): + request = gcd_session.DetectIntentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if session is not None: + request.session = session + if query_input is not None: + request.query_input = query_input + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.detect_intent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("session", request.session), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def streaming_detect_intent(self, + requests: Iterator[session.StreamingDetectIntentRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Iterable[session.StreamingDetectIntentResponse]: + r"""Processes a natural language query in audio format in a + streaming fashion and returns structured, actionable data as a + result. This method is only available via the gRPC API (not + REST). + + If you might use `Agent + Assist `__ or + other CCAI products now or in the future, consider using + [StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent] + instead of ``StreamingDetectIntent``. + ``StreamingAnalyzeContent`` has additional functionality for + Agent Assist and other CCAI products. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Args: + requests (Iterator[google.cloud.dialogflow_v2.types.StreamingDetectIntentRequest]): + The request object iterator. The top-level message sent by the + client to the + [Sessions.StreamingDetectIntent][google.cloud.dialogflow.v2.Sessions.StreamingDetectIntent] + method. + Multiple request messages should be sent in order: + + 1. The first message must contain + [session][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.session], + [query_input][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_input] + plus optionally + [query_params][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_params]. + If the client wants to receive an audio response, it + should also contain + [output_audio_config][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.output_audio_config]. + The message must not contain + [input_audio][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.input_audio]. + 2. If + [query_input][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_input] + was set to + [query_input.audio_config][google.cloud.dialogflow.v2.InputAudioConfig], + all subsequent messages must contain + [input_audio][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.input_audio] + to continue with Speech recognition. + If you decide to rather detect an intent from text + input after you already started Speech recognition, + please send a message with + [query_input.text][google.cloud.dialogflow.v2.QueryInput.text]. + However, note that: + + * Dialogflow will bill you for the audio duration so + far. * Dialogflow discards all Speech recognition + results in favor of the input text. + * Dialogflow will use the language code from the + first message. + After you sent all input, you must half-close or abort + the request stream. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + Iterable[google.cloud.dialogflow_v2.types.StreamingDetectIntentResponse]: + The top-level message returned from the + StreamingDetectIntent method. + + Multiple response messages can be returned in order: + + 1. If the StreamingDetectIntentRequest.input_audio + field was set, the recognition_result field is + populated for one or more messages. See the + [StreamingRecognitionResult][google.cloud.dialogflow.v2.StreamingRecognitionResult] + message for details about the result message + sequence. + 2. The next message contains response_id, + query_result and optionally webhook_status if a + WebHook was called. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.streaming_detect_intent] + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SessionsClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/__init__.py new file mode 100644 index 000000000..fde19f616 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/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 SessionsTransport +from .grpc import SessionsGrpcTransport +from .grpc_asyncio import SessionsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SessionsTransport]] +_transport_registry['grpc'] = SessionsGrpcTransport +_transport_registry['grpc_asyncio'] = SessionsGrpcAsyncIOTransport + +__all__ = ( + 'SessionsTransport', + 'SessionsGrpcTransport', + 'SessionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/base.py new file mode 100644 index 000000000..4cd0a7287 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/base.py @@ -0,0 +1,168 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.types import session +from google.cloud.dialogflow_v2.types import session as gcd_session + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class SessionsTransport(abc.ABC): + """Abstract transport class for Sessions.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.detect_intent: gapic_v1.method.wrap_method( + self.detect_intent, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=220.0, + ), + default_timeout=220.0, + client_info=client_info, + ), + self.streaming_detect_intent: gapic_v1.method.wrap_method( + self.streaming_detect_intent, + default_timeout=220.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def detect_intent(self) -> Callable[ + [gcd_session.DetectIntentRequest], + Union[ + gcd_session.DetectIntentResponse, + Awaitable[gcd_session.DetectIntentResponse] + ]]: + raise NotImplementedError() + + @property + def streaming_detect_intent(self) -> Callable[ + [session.StreamingDetectIntentRequest], + Union[ + session.StreamingDetectIntentResponse, + Awaitable[session.StreamingDetectIntentResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'SessionsTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/grpc.py new file mode 100644 index 000000000..42106b519 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/grpc.py @@ -0,0 +1,313 @@ +# -*- 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 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import session +from google.cloud.dialogflow_v2.types import session as gcd_session +from .base import SessionsTransport, DEFAULT_CLIENT_INFO + + +class SessionsGrpcTransport(SessionsTransport): + """gRPC backend transport for Sessions. + + A service used for session interactions. + + For more information, see the `API interactions + guide `__. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 = 'dialogflow.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 detect_intent(self) -> Callable[ + [gcd_session.DetectIntentRequest], + gcd_session.DetectIntentResponse]: + r"""Return a callable for the detect intent method over gRPC. + + Processes a natural language query and returns structured, + actionable data as a result. This method is not idempotent, + because it may cause contexts and session entity types to be + updated, which in turn might affect results of future queries. + + If you might use `Agent + Assist `__ or + other CCAI products now or in the future, consider using + [AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent] + instead of ``DetectIntent``. ``AnalyzeContent`` has additional + functionality for Agent Assist and other CCAI products. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Returns: + Callable[[~.DetectIntentRequest], + ~.DetectIntentResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'detect_intent' not in self._stubs: + self._stubs['detect_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Sessions/DetectIntent', + request_serializer=gcd_session.DetectIntentRequest.serialize, + response_deserializer=gcd_session.DetectIntentResponse.deserialize, + ) + return self._stubs['detect_intent'] + + @property + def streaming_detect_intent(self) -> Callable[ + [session.StreamingDetectIntentRequest], + session.StreamingDetectIntentResponse]: + r"""Return a callable for the streaming detect intent method over gRPC. + + Processes a natural language query in audio format in a + streaming fashion and returns structured, actionable data as a + result. This method is only available via the gRPC API (not + REST). + + If you might use `Agent + Assist `__ or + other CCAI products now or in the future, consider using + [StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent] + instead of ``StreamingDetectIntent``. + ``StreamingAnalyzeContent`` has additional functionality for + Agent Assist and other CCAI products. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Returns: + Callable[[~.StreamingDetectIntentRequest], + ~.StreamingDetectIntentResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'streaming_detect_intent' not in self._stubs: + self._stubs['streaming_detect_intent'] = self.grpc_channel.stream_stream( + '/google.cloud.dialogflow.v2.Sessions/StreamingDetectIntent', + request_serializer=session.StreamingDetectIntentRequest.serialize, + response_deserializer=session.StreamingDetectIntentResponse.deserialize, + ) + return self._stubs['streaming_detect_intent'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'SessionsGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/grpc_asyncio.py new file mode 100644 index 000000000..7d7e7c6e3 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/grpc_asyncio.py @@ -0,0 +1,317 @@ +# -*- 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 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import session +from google.cloud.dialogflow_v2.types import session as gcd_session +from .base import SessionsTransport, DEFAULT_CLIENT_INFO +from .grpc import SessionsGrpcTransport + + +class SessionsGrpcAsyncIOTransport(SessionsTransport): + """gRPC AsyncIO backend transport for Sessions. + + A service used for session interactions. + + For more information, see the `API interactions + guide `__. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 detect_intent(self) -> Callable[ + [gcd_session.DetectIntentRequest], + Awaitable[gcd_session.DetectIntentResponse]]: + r"""Return a callable for the detect intent method over gRPC. + + Processes a natural language query and returns structured, + actionable data as a result. This method is not idempotent, + because it may cause contexts and session entity types to be + updated, which in turn might affect results of future queries. + + If you might use `Agent + Assist `__ or + other CCAI products now or in the future, consider using + [AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent] + instead of ``DetectIntent``. ``AnalyzeContent`` has additional + functionality for Agent Assist and other CCAI products. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Returns: + Callable[[~.DetectIntentRequest], + Awaitable[~.DetectIntentResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'detect_intent' not in self._stubs: + self._stubs['detect_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Sessions/DetectIntent', + request_serializer=gcd_session.DetectIntentRequest.serialize, + response_deserializer=gcd_session.DetectIntentResponse.deserialize, + ) + return self._stubs['detect_intent'] + + @property + def streaming_detect_intent(self) -> Callable[ + [session.StreamingDetectIntentRequest], + Awaitable[session.StreamingDetectIntentResponse]]: + r"""Return a callable for the streaming detect intent method over gRPC. + + Processes a natural language query in audio format in a + streaming fashion and returns structured, actionable data as a + result. This method is only available via the gRPC API (not + REST). + + If you might use `Agent + Assist `__ or + other CCAI products now or in the future, consider using + [StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent] + instead of ``StreamingDetectIntent``. + ``StreamingAnalyzeContent`` has additional functionality for + Agent Assist and other CCAI products. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Returns: + Callable[[~.StreamingDetectIntentRequest], + Awaitable[~.StreamingDetectIntentResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'streaming_detect_intent' not in self._stubs: + self._stubs['streaming_detect_intent'] = self.grpc_channel.stream_stream( + '/google.cloud.dialogflow.v2.Sessions/StreamingDetectIntent', + request_serializer=session.StreamingDetectIntentRequest.serialize, + response_deserializer=session.StreamingDetectIntentResponse.deserialize, + ) + return self._stubs['streaming_detect_intent'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'SessionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/__init__.py new file mode 100644 index 000000000..630246bde --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/__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 VersionsClient +from .async_client import VersionsAsyncClient + +__all__ = ( + 'VersionsClient', + 'VersionsAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/async_client.py new file mode 100644 index 000000000..7c545d045 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/async_client.py @@ -0,0 +1,646 @@ +# -*- 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 + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2.services.versions import pagers +from google.cloud.dialogflow_v2.types import version +from google.cloud.dialogflow_v2.types import version as gcd_version +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport +from .client import VersionsClient + + +class VersionsAsyncClient: + """Service for managing [Versions][google.cloud.dialogflow.v2.Version].""" + + _client: VersionsClient + + DEFAULT_ENDPOINT = VersionsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = VersionsClient.DEFAULT_MTLS_ENDPOINT + + version_path = staticmethod(VersionsClient.version_path) + parse_version_path = staticmethod(VersionsClient.parse_version_path) + common_billing_account_path = staticmethod(VersionsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(VersionsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(VersionsClient.common_folder_path) + parse_common_folder_path = staticmethod(VersionsClient.parse_common_folder_path) + common_organization_path = staticmethod(VersionsClient.common_organization_path) + parse_common_organization_path = staticmethod(VersionsClient.parse_common_organization_path) + common_project_path = staticmethod(VersionsClient.common_project_path) + parse_common_project_path = staticmethod(VersionsClient.parse_common_project_path) + common_location_path = staticmethod(VersionsClient.common_location_path) + parse_common_location_path = staticmethod(VersionsClient.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: + VersionsAsyncClient: The constructed client. + """ + return VersionsClient.from_service_account_info.__func__(VersionsAsyncClient, 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: + VersionsAsyncClient: The constructed client. + """ + return VersionsClient.from_service_account_file.__func__(VersionsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> VersionsTransport: + """Returns the transport used by the client instance. + + Returns: + VersionsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(VersionsClient).get_transport_class, type(VersionsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, VersionsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the versions 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, ~.VersionsTransport]): 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 = VersionsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_versions(self, + request: Union[version.ListVersionsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVersionsAsyncPager: + r"""Returns the list of all versions of the specified + agent. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListVersionsRequest, dict]): + The request object. The request message for + [Versions.ListVersions][google.cloud.dialogflow.v2.Versions.ListVersions]. + parent (:class:`str`): + Required. The agent to list all versions from. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + 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.dialogflow_v2.services.versions.pagers.ListVersionsAsyncPager: + The response message for + [Versions.ListVersions][google.cloud.dialogflow.v2.Versions.ListVersions]. + + 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 = version.ListVersionsRequest(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_versions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListVersionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_version(self, + request: Union[version.GetVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> version.Version: + r"""Retrieves the specified agent version. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetVersionRequest, dict]): + The request object. The request message for + [Versions.GetVersion][google.cloud.dialogflow.v2.Versions.GetVersion]. + name (:class:`str`): + Required. The name of the version. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + 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.dialogflow_v2.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # 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 = version.GetVersionRequest(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_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_version(self, + request: Union[gcd_version.CreateVersionRequest, dict] = None, + *, + parent: str = None, + version: gcd_version.Version = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: + r"""Creates an agent version. + The new version points to the agent instance in the + "default" environment. + + Args: + request (Union[google.cloud.dialogflow_v2.types.CreateVersionRequest, dict]): + The request object. The request message for + [Versions.CreateVersion][google.cloud.dialogflow.v2.Versions.CreateVersion]. + parent (:class:`str`): + Required. The agent to create a version for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + version (:class:`google.cloud.dialogflow_v2.types.Version`): + Required. The version to create. + This corresponds to the ``version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # 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, version]) + if request is 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 = gcd_version.CreateVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if version is not None: + request.version = version + + # 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_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_version(self, + request: Union[gcd_version.UpdateVersionRequest, dict] = None, + *, + version: gcd_version.Version = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: + r"""Updates the specified agent version. + Note that this method does not allow you to update the + state of the agent the given version points to. It + allows you to update only mutable properties of the + version resource. + + Args: + request (Union[google.cloud.dialogflow_v2.types.UpdateVersionRequest, dict]): + The request object. The request message for + [Versions.UpdateVersion][google.cloud.dialogflow.v2.Versions.UpdateVersion]. + version (:class:`google.cloud.dialogflow_v2.types.Version`): + Required. The version to update. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + This corresponds to the ``version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # 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([version, 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 = gcd_version.UpdateVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if version is not None: + request.version = version + 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_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("version.name", request.version.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_version(self, + request: Union[version.DeleteVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Delete the specified agent version. + + Args: + request (Union[google.cloud.dialogflow_v2.types.DeleteVersionRequest, dict]): + The request object. The request message for + [Versions.DeleteVersion][google.cloud.dialogflow.v2.Versions.DeleteVersion]. + name (:class:`str`): + Required. The name of the version to delete. Supported + formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + 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 = version.DeleteVersionRequest(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_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "VersionsAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/client.py new file mode 100644 index 000000000..cd15de339 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/client.py @@ -0,0 +1,844 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2.services.versions import pagers +from google.cloud.dialogflow_v2.types import version +from google.cloud.dialogflow_v2.types import version as gcd_version +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import VersionsGrpcTransport +from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport + + +class VersionsClientMeta(type): + """Metaclass for the Versions 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[VersionsTransport]] + _transport_registry["grpc"] = VersionsGrpcTransport + _transport_registry["grpc_asyncio"] = VersionsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[VersionsTransport]: + """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 VersionsClient(metaclass=VersionsClientMeta): + """Service for managing [Versions][google.cloud.dialogflow.v2.Version].""" + + @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 = "dialogflow.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: + VersionsClient: 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: + VersionsClient: 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) -> VersionsTransport: + """Returns the transport used by the client instance. + + Returns: + VersionsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def version_path(project: str,version: str,) -> str: + """Returns a fully-qualified version string.""" + return "projects/{project}/agent/versions/{version}".format(project=project, version=version, ) + + @staticmethod + def parse_version_path(path: str) -> Dict[str,str]: + """Parses a version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/versions/(?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, VersionsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the versions 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, VersionsTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, VersionsTransport): + # transport is a VersionsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_versions(self, + request: Union[version.ListVersionsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVersionsPager: + r"""Returns the list of all versions of the specified + agent. + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListVersionsRequest, dict]): + The request object. The request message for + [Versions.ListVersions][google.cloud.dialogflow.v2.Versions.ListVersions]. + parent (str): + Required. The agent to list all versions from. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + 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.dialogflow_v2.services.versions.pagers.ListVersionsPager: + The response message for + [Versions.ListVersions][google.cloud.dialogflow.v2.Versions.ListVersions]. + + 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 version.ListVersionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, version.ListVersionsRequest): + request = version.ListVersionsRequest(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_versions] + + # Certain 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.ListVersionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_version(self, + request: Union[version.GetVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> version.Version: + r"""Retrieves the specified agent version. + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetVersionRequest, dict]): + The request object. The request message for + [Versions.GetVersion][google.cloud.dialogflow.v2.Versions.GetVersion]. + name (str): + Required. The name of the version. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + 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.dialogflow_v2.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # 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 version.GetVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, version.GetVersionRequest): + request = version.GetVersionRequest(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_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_version(self, + request: Union[gcd_version.CreateVersionRequest, dict] = None, + *, + parent: str = None, + version: gcd_version.Version = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: + r"""Creates an agent version. + The new version points to the agent instance in the + "default" environment. + + Args: + request (Union[google.cloud.dialogflow_v2.types.CreateVersionRequest, dict]): + The request object. The request message for + [Versions.CreateVersion][google.cloud.dialogflow.v2.Versions.CreateVersion]. + parent (str): + Required. The agent to create a version for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + version (google.cloud.dialogflow_v2.types.Version): + Required. The version to create. + This corresponds to the ``version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # 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, version]) + if request is 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 gcd_version.CreateVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_version.CreateVersionRequest): + request = gcd_version.CreateVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if version is not None: + request.version = version + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_version(self, + request: Union[gcd_version.UpdateVersionRequest, dict] = None, + *, + version: gcd_version.Version = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: + r"""Updates the specified agent version. + Note that this method does not allow you to update the + state of the agent the given version points to. It + allows you to update only mutable properties of the + version resource. + + Args: + request (Union[google.cloud.dialogflow_v2.types.UpdateVersionRequest, dict]): + The request object. The request message for + [Versions.UpdateVersion][google.cloud.dialogflow.v2.Versions.UpdateVersion]. + version (google.cloud.dialogflow_v2.types.Version): + Required. The version to update. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + This corresponds to the ``version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # 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([version, 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 gcd_version.UpdateVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_version.UpdateVersionRequest): + request = gcd_version.UpdateVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if version is not None: + request.version = version + 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_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("version.name", request.version.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_version(self, + request: Union[version.DeleteVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Delete the specified agent version. + + Args: + request (Union[google.cloud.dialogflow_v2.types.DeleteVersionRequest, dict]): + The request object. The request message for + [Versions.DeleteVersion][google.cloud.dialogflow.v2.Versions.DeleteVersion]. + name (str): + Required. The name of the version to delete. Supported + formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + 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 version.DeleteVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, version.DeleteVersionRequest): + request = version.DeleteVersionRequest(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_version] + + # Certain 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 __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "VersionsClient", +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/pagers.py new file mode 100644 index 000000000..72f9c328d --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflow_v2.types import version + + +class ListVersionsPager: + """A pager for iterating through ``list_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListVersionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``versions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListVersions`` requests and continue to iterate + through the ``versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListVersionsResponse` + 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[..., version.ListVersionsResponse], + request: version.ListVersionsRequest, + response: version.ListVersionsResponse, + *, + 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.dialogflow_v2.types.ListVersionsRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListVersionsResponse): + 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 = version.ListVersionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[version.ListVersionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[version.Version]: + for page in self.pages: + yield from page.versions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListVersionsAsyncPager: + """A pager for iterating through ``list_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListVersionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``versions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListVersions`` requests and continue to iterate + through the ``versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListVersionsResponse` + 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[version.ListVersionsResponse]], + request: version.ListVersionsRequest, + response: version.ListVersionsResponse, + *, + 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.dialogflow_v2.types.ListVersionsRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListVersionsResponse): + 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 = version.ListVersionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[version.ListVersionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[version.Version]: + async def async_generator(): + async for page in self.pages: + for response in page.versions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/__init__.py new file mode 100644 index 000000000..dfb70ce95 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/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 VersionsTransport +from .grpc import VersionsGrpcTransport +from .grpc_asyncio import VersionsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[VersionsTransport]] +_transport_registry['grpc'] = VersionsGrpcTransport +_transport_registry['grpc_asyncio'] = VersionsGrpcAsyncIOTransport + +__all__ = ( + 'VersionsTransport', + 'VersionsGrpcTransport', + 'VersionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/base.py new file mode 100644 index 000000000..45a789314 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/base.py @@ -0,0 +1,205 @@ +# -*- 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.types import version +from google.cloud.dialogflow_v2.types import version as gcd_version +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-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class VersionsTransport(abc.ABC): + """Abstract transport class for Versions.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_versions: gapic_v1.method.wrap_method( + self.list_versions, + default_timeout=None, + client_info=client_info, + ), + self.get_version: gapic_v1.method.wrap_method( + self.get_version, + default_timeout=None, + client_info=client_info, + ), + self.create_version: gapic_v1.method.wrap_method( + self.create_version, + default_timeout=None, + client_info=client_info, + ), + self.update_version: gapic_v1.method.wrap_method( + self.update_version, + default_timeout=None, + client_info=client_info, + ), + self.delete_version: gapic_v1.method.wrap_method( + self.delete_version, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_versions(self) -> Callable[ + [version.ListVersionsRequest], + Union[ + version.ListVersionsResponse, + Awaitable[version.ListVersionsResponse] + ]]: + raise NotImplementedError() + + @property + def get_version(self) -> Callable[ + [version.GetVersionRequest], + Union[ + version.Version, + Awaitable[version.Version] + ]]: + raise NotImplementedError() + + @property + def create_version(self) -> Callable[ + [gcd_version.CreateVersionRequest], + Union[ + gcd_version.Version, + Awaitable[gcd_version.Version] + ]]: + raise NotImplementedError() + + @property + def update_version(self) -> Callable[ + [gcd_version.UpdateVersionRequest], + Union[ + gcd_version.Version, + Awaitable[gcd_version.Version] + ]]: + raise NotImplementedError() + + @property + def delete_version(self) -> Callable[ + [version.DeleteVersionRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'VersionsTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/grpc.py new file mode 100644 index 000000000..69b1e465f --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/grpc.py @@ -0,0 +1,367 @@ +# -*- 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 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import version +from google.cloud.dialogflow_v2.types import version as gcd_version +from google.protobuf import empty_pb2 # type: ignore +from .base import VersionsTransport, DEFAULT_CLIENT_INFO + + +class VersionsGrpcTransport(VersionsTransport): + """gRPC backend transport for Versions. + + Service for managing [Versions][google.cloud.dialogflow.v2.Version]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 = 'dialogflow.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 list_versions(self) -> Callable[ + [version.ListVersionsRequest], + version.ListVersionsResponse]: + r"""Return a callable for the list versions method over gRPC. + + Returns the list of all versions of the specified + agent. + + Returns: + Callable[[~.ListVersionsRequest], + ~.ListVersionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_versions' not in self._stubs: + self._stubs['list_versions'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Versions/ListVersions', + request_serializer=version.ListVersionsRequest.serialize, + response_deserializer=version.ListVersionsResponse.deserialize, + ) + return self._stubs['list_versions'] + + @property + def get_version(self) -> Callable[ + [version.GetVersionRequest], + version.Version]: + r"""Return a callable for the get version method over gRPC. + + Retrieves the specified agent version. + + Returns: + Callable[[~.GetVersionRequest], + ~.Version]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_version' not in self._stubs: + self._stubs['get_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Versions/GetVersion', + request_serializer=version.GetVersionRequest.serialize, + response_deserializer=version.Version.deserialize, + ) + return self._stubs['get_version'] + + @property + def create_version(self) -> Callable[ + [gcd_version.CreateVersionRequest], + gcd_version.Version]: + r"""Return a callable for the create version method over gRPC. + + Creates an agent version. + The new version points to the agent instance in the + "default" environment. + + Returns: + Callable[[~.CreateVersionRequest], + ~.Version]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_version' not in self._stubs: + self._stubs['create_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Versions/CreateVersion', + request_serializer=gcd_version.CreateVersionRequest.serialize, + response_deserializer=gcd_version.Version.deserialize, + ) + return self._stubs['create_version'] + + @property + def update_version(self) -> Callable[ + [gcd_version.UpdateVersionRequest], + gcd_version.Version]: + r"""Return a callable for the update version method over gRPC. + + Updates the specified agent version. + Note that this method does not allow you to update the + state of the agent the given version points to. It + allows you to update only mutable properties of the + version resource. + + Returns: + Callable[[~.UpdateVersionRequest], + ~.Version]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_version' not in self._stubs: + self._stubs['update_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Versions/UpdateVersion', + request_serializer=gcd_version.UpdateVersionRequest.serialize, + response_deserializer=gcd_version.Version.deserialize, + ) + return self._stubs['update_version'] + + @property + def delete_version(self) -> Callable[ + [version.DeleteVersionRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete version method over gRPC. + + Delete the specified agent version. + + Returns: + Callable[[~.DeleteVersionRequest], + ~.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_version' not in self._stubs: + self._stubs['delete_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Versions/DeleteVersion', + request_serializer=version.DeleteVersionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_version'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'VersionsGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/grpc_asyncio.py new file mode 100644 index 000000000..8d15f7ed0 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/grpc_asyncio.py @@ -0,0 +1,371 @@ +# -*- 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 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import version +from google.cloud.dialogflow_v2.types import version as gcd_version +from google.protobuf import empty_pb2 # type: ignore +from .base import VersionsTransport, DEFAULT_CLIENT_INFO +from .grpc import VersionsGrpcTransport + + +class VersionsGrpcAsyncIOTransport(VersionsTransport): + """gRPC AsyncIO backend transport for Versions. + + Service for managing [Versions][google.cloud.dialogflow.v2.Version]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 list_versions(self) -> Callable[ + [version.ListVersionsRequest], + Awaitable[version.ListVersionsResponse]]: + r"""Return a callable for the list versions method over gRPC. + + Returns the list of all versions of the specified + agent. + + Returns: + Callable[[~.ListVersionsRequest], + Awaitable[~.ListVersionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_versions' not in self._stubs: + self._stubs['list_versions'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Versions/ListVersions', + request_serializer=version.ListVersionsRequest.serialize, + response_deserializer=version.ListVersionsResponse.deserialize, + ) + return self._stubs['list_versions'] + + @property + def get_version(self) -> Callable[ + [version.GetVersionRequest], + Awaitable[version.Version]]: + r"""Return a callable for the get version method over gRPC. + + Retrieves the specified agent version. + + Returns: + Callable[[~.GetVersionRequest], + Awaitable[~.Version]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_version' not in self._stubs: + self._stubs['get_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Versions/GetVersion', + request_serializer=version.GetVersionRequest.serialize, + response_deserializer=version.Version.deserialize, + ) + return self._stubs['get_version'] + + @property + def create_version(self) -> Callable[ + [gcd_version.CreateVersionRequest], + Awaitable[gcd_version.Version]]: + r"""Return a callable for the create version method over gRPC. + + Creates an agent version. + The new version points to the agent instance in the + "default" environment. + + Returns: + Callable[[~.CreateVersionRequest], + Awaitable[~.Version]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_version' not in self._stubs: + self._stubs['create_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Versions/CreateVersion', + request_serializer=gcd_version.CreateVersionRequest.serialize, + response_deserializer=gcd_version.Version.deserialize, + ) + return self._stubs['create_version'] + + @property + def update_version(self) -> Callable[ + [gcd_version.UpdateVersionRequest], + Awaitable[gcd_version.Version]]: + r"""Return a callable for the update version method over gRPC. + + Updates the specified agent version. + Note that this method does not allow you to update the + state of the agent the given version points to. It + allows you to update only mutable properties of the + version resource. + + Returns: + Callable[[~.UpdateVersionRequest], + Awaitable[~.Version]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_version' not in self._stubs: + self._stubs['update_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Versions/UpdateVersion', + request_serializer=gcd_version.UpdateVersionRequest.serialize, + response_deserializer=gcd_version.Version.deserialize, + ) + return self._stubs['update_version'] + + @property + def delete_version(self) -> Callable[ + [version.DeleteVersionRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete version method over gRPC. + + Delete the specified agent version. + + Returns: + Callable[[~.DeleteVersionRequest], + 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_version' not in self._stubs: + self._stubs['delete_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2.Versions/DeleteVersion', + request_serializer=version.DeleteVersionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_version'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'VersionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/__init__.py new file mode 100644 index 000000000..ea4c0614f --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/__init__.py @@ -0,0 +1,406 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .agent import ( + Agent, + DeleteAgentRequest, + ExportAgentRequest, + ExportAgentResponse, + GetAgentRequest, + GetValidationResultRequest, + ImportAgentRequest, + RestoreAgentRequest, + SearchAgentsRequest, + SearchAgentsResponse, + SetAgentRequest, + TrainAgentRequest, +) +from .answer_record import ( + AgentAssistantFeedback, + AgentAssistantRecord, + AnswerFeedback, + AnswerRecord, + ListAnswerRecordsRequest, + ListAnswerRecordsResponse, + UpdateAnswerRecordRequest, +) +from .audio_config import ( + InputAudioConfig, + OutputAudioConfig, + SpeechContext, + SpeechToTextConfig, + SpeechWordInfo, + SynthesizeSpeechConfig, + VoiceSelectionParams, + AudioEncoding, + OutputAudioEncoding, + SpeechModelVariant, + SsmlVoiceGender, +) +from .context import ( + Context, + CreateContextRequest, + DeleteAllContextsRequest, + DeleteContextRequest, + GetContextRequest, + ListContextsRequest, + ListContextsResponse, + UpdateContextRequest, +) +from .conversation import ( + CompleteConversationRequest, + Conversation, + ConversationPhoneNumber, + CreateConversationRequest, + GetConversationRequest, + ListConversationsRequest, + ListConversationsResponse, + ListMessagesRequest, + ListMessagesResponse, +) +from .conversation_event import ( + ConversationEvent, +) +from .conversation_profile import ( + AutomatedAgentConfig, + ConversationProfile, + CreateConversationProfileRequest, + DeleteConversationProfileRequest, + GetConversationProfileRequest, + HumanAgentAssistantConfig, + HumanAgentHandoffConfig, + ListConversationProfilesRequest, + ListConversationProfilesResponse, + LoggingConfig, + NotificationConfig, + SuggestionFeature, + UpdateConversationProfileRequest, +) +from .document import ( + CreateDocumentRequest, + DeleteDocumentRequest, + Document, + ExportDocumentRequest, + GetDocumentRequest, + KnowledgeOperationMetadata, + ListDocumentsRequest, + ListDocumentsResponse, + ReloadDocumentRequest, + UpdateDocumentRequest, +) +from .entity_type import ( + BatchCreateEntitiesRequest, + BatchDeleteEntitiesRequest, + BatchDeleteEntityTypesRequest, + BatchUpdateEntitiesRequest, + BatchUpdateEntityTypesRequest, + BatchUpdateEntityTypesResponse, + CreateEntityTypeRequest, + DeleteEntityTypeRequest, + EntityType, + EntityTypeBatch, + GetEntityTypeRequest, + ListEntityTypesRequest, + ListEntityTypesResponse, + UpdateEntityTypeRequest, +) +from .environment import ( + CreateEnvironmentRequest, + DeleteEnvironmentRequest, + Environment, + EnvironmentHistory, + GetEnvironmentHistoryRequest, + GetEnvironmentRequest, + ListEnvironmentsRequest, + ListEnvironmentsResponse, + TextToSpeechSettings, + UpdateEnvironmentRequest, +) +from .fulfillment import ( + Fulfillment, + GetFulfillmentRequest, + UpdateFulfillmentRequest, +) +from .gcs import ( + GcsDestination, +) +from .human_agent_assistant_event import ( + HumanAgentAssistantEvent, +) +from .intent import ( + BatchDeleteIntentsRequest, + BatchUpdateIntentsRequest, + BatchUpdateIntentsResponse, + CreateIntentRequest, + DeleteIntentRequest, + GetIntentRequest, + Intent, + IntentBatch, + ListIntentsRequest, + ListIntentsResponse, + UpdateIntentRequest, + IntentView, +) +from .knowledge_base import ( + CreateKnowledgeBaseRequest, + DeleteKnowledgeBaseRequest, + GetKnowledgeBaseRequest, + KnowledgeBase, + ListKnowledgeBasesRequest, + ListKnowledgeBasesResponse, + UpdateKnowledgeBaseRequest, +) +from .participant import ( + AnalyzeContentRequest, + AnalyzeContentResponse, + AnnotatedMessagePart, + ArticleAnswer, + AssistQueryParameters, + AutomatedAgentReply, + CreateParticipantRequest, + DtmfParameters, + FaqAnswer, + GetParticipantRequest, + ListParticipantsRequest, + ListParticipantsResponse, + Message, + MessageAnnotation, + OutputAudio, + Participant, + SuggestArticlesRequest, + SuggestArticlesResponse, + SuggestFaqAnswersRequest, + SuggestFaqAnswersResponse, + SuggestionResult, + UpdateParticipantRequest, +) +from .session import ( + DetectIntentRequest, + DetectIntentResponse, + EventInput, + QueryInput, + QueryParameters, + QueryResult, + Sentiment, + SentimentAnalysisRequestConfig, + SentimentAnalysisResult, + StreamingDetectIntentRequest, + StreamingDetectIntentResponse, + StreamingRecognitionResult, + TextInput, +) +from .session_entity_type import ( + CreateSessionEntityTypeRequest, + DeleteSessionEntityTypeRequest, + GetSessionEntityTypeRequest, + ListSessionEntityTypesRequest, + ListSessionEntityTypesResponse, + SessionEntityType, + UpdateSessionEntityTypeRequest, +) +from .validation_result import ( + ValidationError, + ValidationResult, +) +from .version import ( + CreateVersionRequest, + DeleteVersionRequest, + GetVersionRequest, + ListVersionsRequest, + ListVersionsResponse, + UpdateVersionRequest, + Version, +) +from .webhook import ( + OriginalDetectIntentRequest, + WebhookRequest, + WebhookResponse, +) + +__all__ = ( + 'Agent', + 'DeleteAgentRequest', + 'ExportAgentRequest', + 'ExportAgentResponse', + 'GetAgentRequest', + 'GetValidationResultRequest', + 'ImportAgentRequest', + 'RestoreAgentRequest', + 'SearchAgentsRequest', + 'SearchAgentsResponse', + 'SetAgentRequest', + 'TrainAgentRequest', + 'AgentAssistantFeedback', + 'AgentAssistantRecord', + 'AnswerFeedback', + 'AnswerRecord', + 'ListAnswerRecordsRequest', + 'ListAnswerRecordsResponse', + 'UpdateAnswerRecordRequest', + 'InputAudioConfig', + 'OutputAudioConfig', + 'SpeechContext', + 'SpeechToTextConfig', + 'SpeechWordInfo', + 'SynthesizeSpeechConfig', + 'VoiceSelectionParams', + 'AudioEncoding', + 'OutputAudioEncoding', + 'SpeechModelVariant', + 'SsmlVoiceGender', + 'Context', + 'CreateContextRequest', + 'DeleteAllContextsRequest', + 'DeleteContextRequest', + 'GetContextRequest', + 'ListContextsRequest', + 'ListContextsResponse', + 'UpdateContextRequest', + 'CompleteConversationRequest', + 'Conversation', + 'ConversationPhoneNumber', + 'CreateConversationRequest', + 'GetConversationRequest', + 'ListConversationsRequest', + 'ListConversationsResponse', + 'ListMessagesRequest', + 'ListMessagesResponse', + 'ConversationEvent', + 'AutomatedAgentConfig', + 'ConversationProfile', + 'CreateConversationProfileRequest', + 'DeleteConversationProfileRequest', + 'GetConversationProfileRequest', + 'HumanAgentAssistantConfig', + 'HumanAgentHandoffConfig', + 'ListConversationProfilesRequest', + 'ListConversationProfilesResponse', + 'LoggingConfig', + 'NotificationConfig', + 'SuggestionFeature', + 'UpdateConversationProfileRequest', + 'CreateDocumentRequest', + 'DeleteDocumentRequest', + 'Document', + 'ExportDocumentRequest', + 'GetDocumentRequest', + 'KnowledgeOperationMetadata', + 'ListDocumentsRequest', + 'ListDocumentsResponse', + 'ReloadDocumentRequest', + 'UpdateDocumentRequest', + 'BatchCreateEntitiesRequest', + 'BatchDeleteEntitiesRequest', + 'BatchDeleteEntityTypesRequest', + 'BatchUpdateEntitiesRequest', + 'BatchUpdateEntityTypesRequest', + 'BatchUpdateEntityTypesResponse', + 'CreateEntityTypeRequest', + 'DeleteEntityTypeRequest', + 'EntityType', + 'EntityTypeBatch', + 'GetEntityTypeRequest', + 'ListEntityTypesRequest', + 'ListEntityTypesResponse', + 'UpdateEntityTypeRequest', + 'CreateEnvironmentRequest', + 'DeleteEnvironmentRequest', + 'Environment', + 'EnvironmentHistory', + 'GetEnvironmentHistoryRequest', + 'GetEnvironmentRequest', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'TextToSpeechSettings', + 'UpdateEnvironmentRequest', + 'Fulfillment', + 'GetFulfillmentRequest', + 'UpdateFulfillmentRequest', + 'GcsDestination', + 'HumanAgentAssistantEvent', + 'BatchDeleteIntentsRequest', + 'BatchUpdateIntentsRequest', + 'BatchUpdateIntentsResponse', + 'CreateIntentRequest', + 'DeleteIntentRequest', + 'GetIntentRequest', + 'Intent', + 'IntentBatch', + 'ListIntentsRequest', + 'ListIntentsResponse', + 'UpdateIntentRequest', + 'IntentView', + 'CreateKnowledgeBaseRequest', + 'DeleteKnowledgeBaseRequest', + 'GetKnowledgeBaseRequest', + 'KnowledgeBase', + 'ListKnowledgeBasesRequest', + 'ListKnowledgeBasesResponse', + 'UpdateKnowledgeBaseRequest', + 'AnalyzeContentRequest', + 'AnalyzeContentResponse', + 'AnnotatedMessagePart', + 'ArticleAnswer', + 'AssistQueryParameters', + 'AutomatedAgentReply', + 'CreateParticipantRequest', + 'DtmfParameters', + 'FaqAnswer', + 'GetParticipantRequest', + 'ListParticipantsRequest', + 'ListParticipantsResponse', + 'Message', + 'MessageAnnotation', + 'OutputAudio', + 'Participant', + 'SuggestArticlesRequest', + 'SuggestArticlesResponse', + 'SuggestFaqAnswersRequest', + 'SuggestFaqAnswersResponse', + 'SuggestionResult', + 'UpdateParticipantRequest', + 'DetectIntentRequest', + 'DetectIntentResponse', + 'EventInput', + 'QueryInput', + 'QueryParameters', + 'QueryResult', + 'Sentiment', + 'SentimentAnalysisRequestConfig', + 'SentimentAnalysisResult', + 'StreamingDetectIntentRequest', + 'StreamingDetectIntentResponse', + 'StreamingRecognitionResult', + 'TextInput', + 'CreateSessionEntityTypeRequest', + 'DeleteSessionEntityTypeRequest', + 'GetSessionEntityTypeRequest', + 'ListSessionEntityTypesRequest', + 'ListSessionEntityTypesResponse', + 'SessionEntityType', + 'UpdateSessionEntityTypeRequest', + 'ValidationError', + 'ValidationResult', + 'CreateVersionRequest', + 'DeleteVersionRequest', + 'GetVersionRequest', + 'ListVersionsRequest', + 'ListVersionsResponse', + 'UpdateVersionRequest', + 'Version', + 'OriginalDetectIntentRequest', + 'WebhookRequest', + 'WebhookResponse', +) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/agent.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/agent.py new file mode 100644 index 000000000..4bbded857 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/agent.py @@ -0,0 +1,492 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + 'Agent', + 'GetAgentRequest', + 'SetAgentRequest', + 'DeleteAgentRequest', + 'SearchAgentsRequest', + 'SearchAgentsResponse', + 'TrainAgentRequest', + 'ExportAgentRequest', + 'ExportAgentResponse', + 'ImportAgentRequest', + 'RestoreAgentRequest', + 'GetValidationResultRequest', + }, +) + + +class Agent(proto.Message): + r"""A Dialogflow agent is a virtual agent that handles conversations + with your end-users. It is a natural language understanding module + that understands the nuances of human language. Dialogflow + translates end-user text or audio during a conversation to + structured data that your apps and services can understand. You + design and build a Dialogflow agent to handle the types of + conversations required for your system. + + For more information about agents, see the `Agent + guide `__. + + Attributes: + parent (str): + Required. The project of this agent. Format: + ``projects/``. + display_name (str): + Required. The name of this agent. + default_language_code (str): + Required. The default language of the agent as a language + tag. See `Language + Support `__ + for a list of the currently supported language codes. This + field cannot be set by the ``Update`` method. + supported_language_codes (Sequence[str]): + Optional. The list of all languages supported by this agent + (except for the ``default_language_code``). + time_zone (str): + Required. The time zone of this agent from the `time zone + database `__, e.g., + America/New_York, Europe/Paris. + description (str): + Optional. The description of this agent. + The maximum length is 500 characters. If + exceeded, the request is rejected. + avatar_uri (str): + Optional. The URI of the agent's avatar. Avatars are used + throughout the Dialogflow console and in the self-hosted + `Web + Demo `__ + integration. + enable_logging (bool): + Optional. Determines whether this agent + should log conversation queries. + match_mode (google.cloud.dialogflow_v2.types.Agent.MatchMode): + Optional. Determines how intents are detected + from user queries. + classification_threshold (float): + Optional. To filter out false positive + results and still get variety in matched natural + language inputs for your agent, you can tune the + machine learning classification threshold. If + the returned score value is less than the + threshold value, then a fallback intent will be + triggered or, if there are no fallback intents + defined, no intent will be triggered. The score + values range from 0.0 (completely uncertain) to + 1.0 (completely certain). If set to 0.0, the + default of 0.3 is used. + api_version (google.cloud.dialogflow_v2.types.Agent.ApiVersion): + Optional. API version displayed in Dialogflow + console. If not specified, V2 API is assumed. + Clients are free to query different service + endpoints for different API versions. However, + bots connectors and webhook calls will follow + the specified API version. + tier (google.cloud.dialogflow_v2.types.Agent.Tier): + Optional. The agent tier. If not specified, TIER_STANDARD is + assumed. + """ + class MatchMode(proto.Enum): + r"""Match mode determines how intents are detected from user + queries. + """ + MATCH_MODE_UNSPECIFIED = 0 + MATCH_MODE_HYBRID = 1 + MATCH_MODE_ML_ONLY = 2 + + class ApiVersion(proto.Enum): + r"""API version for the agent.""" + API_VERSION_UNSPECIFIED = 0 + API_VERSION_V1 = 1 + API_VERSION_V2 = 2 + API_VERSION_V2_BETA_1 = 3 + + class Tier(proto.Enum): + r"""Represents the agent tier.""" + TIER_UNSPECIFIED = 0 + TIER_STANDARD = 1 + TIER_ENTERPRISE = 2 + TIER_ENTERPRISE_PLUS = 3 + + parent = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + default_language_code = proto.Field( + proto.STRING, + number=3, + ) + supported_language_codes = proto.RepeatedField( + proto.STRING, + number=4, + ) + time_zone = proto.Field( + proto.STRING, + number=5, + ) + description = proto.Field( + proto.STRING, + number=6, + ) + avatar_uri = proto.Field( + proto.STRING, + number=7, + ) + enable_logging = proto.Field( + proto.BOOL, + number=8, + ) + match_mode = proto.Field( + proto.ENUM, + number=9, + enum=MatchMode, + ) + classification_threshold = proto.Field( + proto.FLOAT, + number=10, + ) + api_version = proto.Field( + proto.ENUM, + number=14, + enum=ApiVersion, + ) + tier = proto.Field( + proto.ENUM, + number=15, + enum=Tier, + ) + + +class GetAgentRequest(proto.Message): + r"""The request message for + [Agents.GetAgent][google.cloud.dialogflow.v2.Agents.GetAgent]. + + Attributes: + parent (str): + Required. The project that the agent to fetch is associated + with. Format: ``projects/``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + + +class SetAgentRequest(proto.Message): + r"""The request message for + [Agents.SetAgent][google.cloud.dialogflow.v2.Agents.SetAgent]. + + Attributes: + agent (google.cloud.dialogflow_v2.types.Agent): + Required. The agent to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which fields + get updated. + """ + + agent = proto.Field( + proto.MESSAGE, + number=1, + message='Agent', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteAgentRequest(proto.Message): + r"""The request message for + [Agents.DeleteAgent][google.cloud.dialogflow.v2.Agents.DeleteAgent]. + + Attributes: + parent (str): + Required. The project that the agent to delete is associated + with. Format: ``projects/``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + + +class SearchAgentsRequest(proto.Message): + r"""The request message for + [Agents.SearchAgents][google.cloud.dialogflow.v2.Agents.SearchAgents]. + + Attributes: + parent (str): + Required. The project to list agents from. Format: + ``projects/``. + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + The next_page_token value returned from a previous list + request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class SearchAgentsResponse(proto.Message): + r"""The response message for + [Agents.SearchAgents][google.cloud.dialogflow.v2.Agents.SearchAgents]. + + Attributes: + agents (Sequence[google.cloud.dialogflow_v2.types.Agent]): + The list of agents. There will be a maximum number of items + returned based on the page_size field in the request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + agents = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Agent', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class TrainAgentRequest(proto.Message): + r"""The request message for + [Agents.TrainAgent][google.cloud.dialogflow.v2.Agents.TrainAgent]. + + Attributes: + parent (str): + Required. The project that the agent to train is associated + with. Format: ``projects/``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + + +class ExportAgentRequest(proto.Message): + r"""The request message for + [Agents.ExportAgent][google.cloud.dialogflow.v2.Agents.ExportAgent]. + + Attributes: + parent (str): + Required. The project that the agent to export is associated + with. Format: ``projects/``. + agent_uri (str): + Required. The `Google Cloud + Storage `__ URI to + export the agent to. The format of this URI must be + ``gs:///``. If left unspecified, + the serialized agent is returned inline. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + agent_uri = proto.Field( + proto.STRING, + number=2, + ) + + +class ExportAgentResponse(proto.Message): + r"""The response message for + [Agents.ExportAgent][google.cloud.dialogflow.v2.Agents.ExportAgent]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + agent_uri (str): + The URI to a file containing the exported agent. This field + is populated only if ``agent_uri`` is specified in + ``ExportAgentRequest``. + + This field is a member of `oneof`_ ``agent``. + agent_content (bytes): + Zip compressed raw byte content for agent. + + This field is a member of `oneof`_ ``agent``. + """ + + agent_uri = proto.Field( + proto.STRING, + number=1, + oneof='agent', + ) + agent_content = proto.Field( + proto.BYTES, + number=2, + oneof='agent', + ) + + +class ImportAgentRequest(proto.Message): + r"""The request message for + [Agents.ImportAgent][google.cloud.dialogflow.v2.Agents.ImportAgent]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The project that the agent to import is associated + with. Format: ``projects/``. + agent_uri (str): + The URI to a Google Cloud Storage file + containing the agent to import. Note: The URI + must start with "gs://". + + This field is a member of `oneof`_ ``agent``. + agent_content (bytes): + Zip compressed raw byte content for agent. + + This field is a member of `oneof`_ ``agent``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + agent_uri = proto.Field( + proto.STRING, + number=2, + oneof='agent', + ) + agent_content = proto.Field( + proto.BYTES, + number=3, + oneof='agent', + ) + + +class RestoreAgentRequest(proto.Message): + r"""The request message for + [Agents.RestoreAgent][google.cloud.dialogflow.v2.Agents.RestoreAgent]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The project that the agent to restore is + associated with. Format: ``projects/``. + agent_uri (str): + The URI to a Google Cloud Storage file + containing the agent to restore. Note: The URI + must start with "gs://". + + This field is a member of `oneof`_ ``agent``. + agent_content (bytes): + Zip compressed raw byte content for agent. + + This field is a member of `oneof`_ ``agent``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + agent_uri = proto.Field( + proto.STRING, + number=2, + oneof='agent', + ) + agent_content = proto.Field( + proto.BYTES, + number=3, + oneof='agent', + ) + + +class GetValidationResultRequest(proto.Message): + r"""The request message for + [Agents.GetValidationResult][google.cloud.dialogflow.v2.Agents.GetValidationResult]. + + Attributes: + parent (str): + Required. The project that the agent is associated with. + Format: ``projects/``. + language_code (str): + Optional. The language for which you want a validation + result. If not specified, the agent's default language is + used. `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/answer_record.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/answer_record.py new file mode 100644 index 000000000..34f9e810b --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/answer_record.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.dialogflow_v2.types import participant +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + 'AnswerRecord', + 'ListAnswerRecordsRequest', + 'ListAnswerRecordsResponse', + 'UpdateAnswerRecordRequest', + 'AnswerFeedback', + 'AgentAssistantFeedback', + 'AgentAssistantRecord', + }, +) + + +class AnswerRecord(proto.Message): + r"""Answer records are records to manage answer history and feedbacks + for Dialogflow. + + Currently, answer record includes: + + - human agent assistant article suggestion + - human agent assistant faq article + + It doesn't include: + + - ``DetectIntent`` intent matching + - ``DetectIntent`` knowledge + + Answer records are not related to the conversation history in the + Dialogflow Console. A Record is generated even when the end-user + disables conversation history in the console. Records are created + when there's a human agent assistant suggestion generated. + + A typical workflow for customers provide feedback to an answer is: + + 1. For human agent assistant, customers get suggestion via + ListSuggestions API. Together with the answers, + [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] + are returned to the customers. + 2. The customer uses the + [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] + to call the [UpdateAnswerRecord][] method to send feedback about + a specific answer that they believe is wrong. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + The unique identifier of this answer record. Format: + ``projects//locations//answerRecords/``. + answer_feedback (google.cloud.dialogflow_v2.types.AnswerFeedback): + Required. The AnswerFeedback for this record. You can set + this with + [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2.AnswerRecords.UpdateAnswerRecord] + in order to give us feedback about this answer. + agent_assistant_record (google.cloud.dialogflow_v2.types.AgentAssistantRecord): + Output only. The record for human agent + assistant. + + This field is a member of `oneof`_ ``record``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + answer_feedback = proto.Field( + proto.MESSAGE, + number=2, + message='AnswerFeedback', + ) + agent_assistant_record = proto.Field( + proto.MESSAGE, + number=4, + oneof='record', + message='AgentAssistantRecord', + ) + + +class ListAnswerRecordsRequest(proto.Message): + r"""Request message for + [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. + + Attributes: + parent (str): + Required. The project to list all answer records for in + reverse chronological order. Format: + ``projects//locations/``. + filter (str): + Required. Filters to restrict results to specific answer + records. Filter on answer record type. Currently predicates + on ``type`` is supported, valid values are + ``ARTICLE_ANSWER``, ``FAQ_ANSWER``. + + For more information about filtering, see `API + Filtering `__. + page_size (int): + Optional. The maximum number of records to + return in a single page. The server may return + fewer records than this. If unspecified, we use + 10. The maximum is 100. + page_token (str): + Optional. The + [ListAnswerRecordsResponse.next_page_token][google.cloud.dialogflow.v2.ListAnswerRecordsResponse.next_page_token] + value returned from a previous list request used to continue + listing on the next page. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class ListAnswerRecordsResponse(proto.Message): + r"""Response message for + [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. + + Attributes: + answer_records (Sequence[google.cloud.dialogflow_v2.types.AnswerRecord]): + The list of answer records. + next_page_token (str): + A token to retrieve next page of results. Or empty if there + are no more results. Pass this value in the + [ListAnswerRecordsRequest.page_token][google.cloud.dialogflow.v2.ListAnswerRecordsRequest.page_token] + field in the subsequent call to ``ListAnswerRecords`` method + to retrieve the next page of results. + """ + + @property + def raw_page(self): + return self + + answer_records = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AnswerRecord', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateAnswerRecordRequest(proto.Message): + r"""Request message for + [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2.AnswerRecords.UpdateAnswerRecord]. + + Attributes: + answer_record (google.cloud.dialogflow_v2.types.AnswerRecord): + Required. Answer record to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. + """ + + answer_record = proto.Field( + proto.MESSAGE, + number=1, + message='AnswerRecord', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class AnswerFeedback(proto.Message): + r"""Represents feedback the customer has about the quality & + correctness of a certain answer in a conversation. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + correctness_level (google.cloud.dialogflow_v2.types.AnswerFeedback.CorrectnessLevel): + The correctness level of the specific answer. + agent_assistant_detail_feedback (google.cloud.dialogflow_v2.types.AgentAssistantFeedback): + Detail feedback of agent assist suggestions. + + This field is a member of `oneof`_ ``detail_feedback``. + clicked (bool): + Indicates whether the answer/item was clicked + by the human agent or not. Default to false. + click_time (google.protobuf.timestamp_pb2.Timestamp): + Time when the answer/item was clicked. + displayed (bool): + Indicates whether the answer/item was + displayed to the human agent in the agent + desktop UI. Default to false. + display_time (google.protobuf.timestamp_pb2.Timestamp): + Time when the answer/item was displayed. + """ + class CorrectnessLevel(proto.Enum): + r"""The correctness level of an answer.""" + CORRECTNESS_LEVEL_UNSPECIFIED = 0 + NOT_CORRECT = 1 + PARTIALLY_CORRECT = 2 + FULLY_CORRECT = 3 + + correctness_level = proto.Field( + proto.ENUM, + number=1, + enum=CorrectnessLevel, + ) + agent_assistant_detail_feedback = proto.Field( + proto.MESSAGE, + number=2, + oneof='detail_feedback', + message='AgentAssistantFeedback', + ) + clicked = proto.Field( + proto.BOOL, + number=3, + ) + click_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + displayed = proto.Field( + proto.BOOL, + number=4, + ) + display_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + +class AgentAssistantFeedback(proto.Message): + r"""Detail feedback of Agent Assist result. + + Attributes: + answer_relevance (google.cloud.dialogflow_v2.types.AgentAssistantFeedback.AnswerRelevance): + Optional. Whether or not the suggested answer is relevant. + + For example: + + - Query: "Can I change my mailing address?" + - Suggested document says: "Items must be + returned/exchanged within 60 days of the purchase date." + - [answer_relevance][google.cloud.dialogflow.v2.AgentAssistantFeedback.answer_relevance]: + [AnswerRelevance.IRRELEVANT][google.cloud.dialogflow.v2.AgentAssistantFeedback.AnswerRelevance.IRRELEVANT] + document_correctness (google.cloud.dialogflow_v2.types.AgentAssistantFeedback.DocumentCorrectness): + Optional. Whether or not the information in the document is + correct. + + For example: + + - Query: "Can I return the package in 2 days once + received?" + - Suggested document says: "Items must be + returned/exchanged within 60 days of the purchase date." + - Ground truth: "No return or exchange is allowed." + - + document_efficiency (google.cloud.dialogflow_v2.types.AgentAssistantFeedback.DocumentEfficiency): + Optional. Whether or not the suggested document is + efficient. For example, if the document is poorly written, + hard to understand, hard to use or too long to find useful + information, + [document_efficiency][google.cloud.dialogflow.v2.AgentAssistantFeedback.document_efficiency] + is + [DocumentEfficiency.INEFFICIENT][google.cloud.dialogflow.v2.AgentAssistantFeedback.DocumentEfficiency.INEFFICIENT]. + """ + class AnswerRelevance(proto.Enum): + r"""Relevance of an answer.""" + ANSWER_RELEVANCE_UNSPECIFIED = 0 + IRRELEVANT = 1 + RELEVANT = 2 + + class DocumentCorrectness(proto.Enum): + r"""Correctness of document.""" + DOCUMENT_CORRECTNESS_UNSPECIFIED = 0 + INCORRECT = 1 + CORRECT = 2 + + class DocumentEfficiency(proto.Enum): + r"""Efficiency of document.""" + DOCUMENT_EFFICIENCY_UNSPECIFIED = 0 + INEFFICIENT = 1 + EFFICIENT = 2 + + answer_relevance = proto.Field( + proto.ENUM, + number=1, + enum=AnswerRelevance, + ) + document_correctness = proto.Field( + proto.ENUM, + number=2, + enum=DocumentCorrectness, + ) + document_efficiency = proto.Field( + proto.ENUM, + number=3, + enum=DocumentEfficiency, + ) + + +class AgentAssistantRecord(proto.Message): + r"""Represents a record of a human agent assist answer. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + article_suggestion_answer (google.cloud.dialogflow_v2.types.ArticleAnswer): + Output only. The article suggestion answer. + + This field is a member of `oneof`_ ``answer``. + faq_answer (google.cloud.dialogflow_v2.types.FaqAnswer): + Output only. The FAQ answer. + + This field is a member of `oneof`_ ``answer``. + """ + + article_suggestion_answer = proto.Field( + proto.MESSAGE, + number=5, + oneof='answer', + message=participant.ArticleAnswer, + ) + faq_answer = proto.Field( + proto.MESSAGE, + number=6, + oneof='answer', + message=participant.FaqAnswer, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/audio_config.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/audio_config.py new file mode 100644 index 000000000..90dd38733 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/audio_config.py @@ -0,0 +1,468 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + 'AudioEncoding', + 'SpeechModelVariant', + 'SsmlVoiceGender', + 'OutputAudioEncoding', + 'SpeechContext', + 'SpeechWordInfo', + 'InputAudioConfig', + 'VoiceSelectionParams', + 'SynthesizeSpeechConfig', + 'OutputAudioConfig', + 'SpeechToTextConfig', + }, +) + + +class AudioEncoding(proto.Enum): + r"""Audio encoding of the audio content sent in the conversational query + request. Refer to the `Cloud Speech API + documentation `__ + for more details. + """ + AUDIO_ENCODING_UNSPECIFIED = 0 + AUDIO_ENCODING_LINEAR_16 = 1 + AUDIO_ENCODING_FLAC = 2 + AUDIO_ENCODING_MULAW = 3 + AUDIO_ENCODING_AMR = 4 + AUDIO_ENCODING_AMR_WB = 5 + AUDIO_ENCODING_OGG_OPUS = 6 + AUDIO_ENCODING_SPEEX_WITH_HEADER_BYTE = 7 + + +class SpeechModelVariant(proto.Enum): + r"""Variant of the specified [Speech + model][google.cloud.dialogflow.v2.InputAudioConfig.model] to use. + + See the `Cloud Speech + documentation `__ + for which models have different variants. For example, the + "phone_call" model has both a standard and an enhanced variant. When + you use an enhanced model, you will generally receive higher quality + results than for a standard model. + """ + SPEECH_MODEL_VARIANT_UNSPECIFIED = 0 + USE_BEST_AVAILABLE = 1 + USE_STANDARD = 2 + USE_ENHANCED = 3 + + +class SsmlVoiceGender(proto.Enum): + r"""Gender of the voice as described in `SSML voice + element `__. + """ + SSML_VOICE_GENDER_UNSPECIFIED = 0 + SSML_VOICE_GENDER_MALE = 1 + SSML_VOICE_GENDER_FEMALE = 2 + SSML_VOICE_GENDER_NEUTRAL = 3 + + +class OutputAudioEncoding(proto.Enum): + r"""Audio encoding of the output audio format in Text-To-Speech.""" + OUTPUT_AUDIO_ENCODING_UNSPECIFIED = 0 + OUTPUT_AUDIO_ENCODING_LINEAR_16 = 1 + OUTPUT_AUDIO_ENCODING_MP3 = 2 + OUTPUT_AUDIO_ENCODING_MP3_64_KBPS = 4 + OUTPUT_AUDIO_ENCODING_OGG_OPUS = 3 + OUTPUT_AUDIO_ENCODING_MULAW = 5 + + +class SpeechContext(proto.Message): + r"""Hints for the speech recognizer to help with recognition in a + specific conversation state. + + Attributes: + phrases (Sequence[str]): + Optional. A list of strings containing words and phrases + that the speech recognizer should recognize with higher + likelihood. + + This list can be used to: + + - improve accuracy for words and phrases you expect the + user to say, e.g. typical commands for your Dialogflow + agent + - add additional words to the speech recognizer vocabulary + - ... + + See the `Cloud Speech + documentation `__ + for usage limits. + boost (float): + Optional. Boost for this context compared to other contexts: + + - If the boost is positive, Dialogflow will increase the + probability that the phrases in this context are + recognized over similar sounding phrases. + - If the boost is unspecified or non-positive, Dialogflow + will not apply any boost. + + Dialogflow recommends that you use boosts in the range (0, + 20] and that you find a value that fits your use case with + binary search. + """ + + phrases = proto.RepeatedField( + proto.STRING, + number=1, + ) + boost = proto.Field( + proto.FLOAT, + number=2, + ) + + +class SpeechWordInfo(proto.Message): + r"""Information for a word recognized by the speech recognizer. + + Attributes: + word (str): + The word this info is for. + start_offset (google.protobuf.duration_pb2.Duration): + Time offset relative to the beginning of the + audio that corresponds to the start of the + spoken word. This is an experimental feature and + the accuracy of the time offset can vary. + end_offset (google.protobuf.duration_pb2.Duration): + Time offset relative to the beginning of the + audio that corresponds to the end of the spoken + word. This is an experimental feature and the + accuracy of the time offset can vary. + confidence (float): + The Speech confidence between 0.0 and 1.0 for + this word. A higher number indicates an + estimated greater likelihood that the recognized + word is correct. The default of 0.0 is a + sentinel value indicating that confidence was + not set. + + This field is not guaranteed to be fully stable + over time for the same audio input. Users should + also not rely on it to always be provided. + """ + + word = proto.Field( + proto.STRING, + number=3, + ) + start_offset = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + end_offset = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + confidence = proto.Field( + proto.FLOAT, + number=4, + ) + + +class InputAudioConfig(proto.Message): + r"""Instructs the speech recognizer how to process the audio + content. + + Attributes: + audio_encoding (google.cloud.dialogflow_v2.types.AudioEncoding): + Required. Audio encoding of the audio content + to process. + sample_rate_hertz (int): + Required. Sample rate (in Hertz) of the audio content sent + in the query. Refer to `Cloud Speech API + documentation `__ + for more details. + language_code (str): + Required. The language of the supplied audio. Dialogflow + does not do translations. See `Language + Support `__ + for a list of the currently supported language codes. Note + that queries in the same session do not necessarily need to + specify the same language. + enable_word_info (bool): + If ``true``, Dialogflow returns + [SpeechWordInfo][google.cloud.dialogflow.v2.SpeechWordInfo] + in + [StreamingRecognitionResult][google.cloud.dialogflow.v2.StreamingRecognitionResult] + with information about the recognized speech words, e.g. + start and end time offsets. If false or unspecified, Speech + doesn't return any word-level information. + phrase_hints (Sequence[str]): + A list of strings containing words and phrases that the + speech recognizer should recognize with higher likelihood. + + See `the Cloud Speech + documentation `__ + for more details. + + This field is deprecated. Please use `speech_contexts <>`__ + instead. If you specify both `phrase_hints <>`__ and + `speech_contexts <>`__, Dialogflow will treat the + `phrase_hints <>`__ as a single additional + `SpeechContext <>`__. + speech_contexts (Sequence[google.cloud.dialogflow_v2.types.SpeechContext]): + Context information to assist speech recognition. + + See `the Cloud Speech + documentation `__ + for more details. + model (str): + Which Speech model to select for the given request. Select + the model best suited to your domain to get best results. If + a model is not explicitly specified, then we auto-select a + model based on the parameters in the InputAudioConfig. If + enhanced speech model is enabled for the agent and an + enhanced version of the specified model for the language + does not exist, then the speech is recognized using the + standard version of the specified model. Refer to `Cloud + Speech API + documentation `__ + for more details. + model_variant (google.cloud.dialogflow_v2.types.SpeechModelVariant): + Which variant of the [Speech + model][google.cloud.dialogflow.v2.InputAudioConfig.model] to + use. + single_utterance (bool): + If ``false`` (default), recognition does not cease until the + client closes the stream. If ``true``, the recognizer will + detect a single spoken utterance in input audio. Recognition + ceases when it detects the audio's voice has stopped or + paused. In this case, once a detected intent is received, + the client should close the stream and start a new request + with a new stream as needed. Note: This setting is relevant + only for streaming methods. Note: When specified, + InputAudioConfig.single_utterance takes precedence over + StreamingDetectIntentRequest.single_utterance. + disable_no_speech_recognized_event (bool): + Only used in + [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent] + and + [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent]. + If ``false`` and recognition doesn't return any result, + trigger ``NO_SPEECH_RECOGNIZED`` event to Dialogflow agent. + """ + + audio_encoding = proto.Field( + proto.ENUM, + number=1, + enum='AudioEncoding', + ) + sample_rate_hertz = proto.Field( + proto.INT32, + number=2, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + enable_word_info = proto.Field( + proto.BOOL, + number=13, + ) + phrase_hints = proto.RepeatedField( + proto.STRING, + number=4, + ) + speech_contexts = proto.RepeatedField( + proto.MESSAGE, + number=11, + message='SpeechContext', + ) + model = proto.Field( + proto.STRING, + number=7, + ) + model_variant = proto.Field( + proto.ENUM, + number=10, + enum='SpeechModelVariant', + ) + single_utterance = proto.Field( + proto.BOOL, + number=8, + ) + disable_no_speech_recognized_event = proto.Field( + proto.BOOL, + number=14, + ) + + +class VoiceSelectionParams(proto.Message): + r"""Description of which voice to use for speech synthesis. + + Attributes: + name (str): + Optional. The name of the voice. If not set, the service + will choose a voice based on the other parameters such as + language_code and + [ssml_gender][google.cloud.dialogflow.v2.VoiceSelectionParams.ssml_gender]. + ssml_gender (google.cloud.dialogflow_v2.types.SsmlVoiceGender): + Optional. The preferred gender of the voice. If not set, the + service will choose a voice based on the other parameters + such as language_code and + [name][google.cloud.dialogflow.v2.VoiceSelectionParams.name]. + Note that this is only a preference, not requirement. If a + voice of the appropriate gender is not available, the + synthesizer should substitute a voice with a different + gender rather than failing the request. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + ssml_gender = proto.Field( + proto.ENUM, + number=2, + enum='SsmlVoiceGender', + ) + + +class SynthesizeSpeechConfig(proto.Message): + r"""Configuration of how speech should be synthesized. + + Attributes: + speaking_rate (float): + Optional. Speaking rate/speed, in the range [0.25, 4.0]. 1.0 + is the normal native speed supported by the specific voice. + 2.0 is twice as fast, and 0.5 is half as fast. If + unset(0.0), defaults to the native 1.0 speed. Any other + values < 0.25 or > 4.0 will return an error. + pitch (float): + Optional. Speaking pitch, in the range [-20.0, 20.0]. 20 + means increase 20 semitones from the original pitch. -20 + means decrease 20 semitones from the original pitch. + volume_gain_db (float): + Optional. Volume gain (in dB) of the normal native volume + supported by the specific voice, in the range [-96.0, 16.0]. + If unset, or set to a value of 0.0 (dB), will play at normal + native signal amplitude. A value of -6.0 (dB) will play at + approximately half the amplitude of the normal native signal + amplitude. A value of +6.0 (dB) will play at approximately + twice the amplitude of the normal native signal amplitude. + We strongly recommend not to exceed +10 (dB) as there's + usually no effective increase in loudness for any value + greater than that. + effects_profile_id (Sequence[str]): + Optional. An identifier which selects 'audio + effects' profiles that are applied on (post + synthesized) text to speech. Effects are applied + on top of each other in the order they are + given. + voice (google.cloud.dialogflow_v2.types.VoiceSelectionParams): + Optional. The desired voice of the + synthesized audio. + """ + + speaking_rate = proto.Field( + proto.DOUBLE, + number=1, + ) + pitch = proto.Field( + proto.DOUBLE, + number=2, + ) + volume_gain_db = proto.Field( + proto.DOUBLE, + number=3, + ) + effects_profile_id = proto.RepeatedField( + proto.STRING, + number=5, + ) + voice = proto.Field( + proto.MESSAGE, + number=4, + message='VoiceSelectionParams', + ) + + +class OutputAudioConfig(proto.Message): + r"""Instructs the speech synthesizer on how to generate the + output audio content. If this audio config is supplied in a + request, it overrides all existing text-to-speech settings + applied to the agent. + + Attributes: + audio_encoding (google.cloud.dialogflow_v2.types.OutputAudioEncoding): + Required. Audio encoding of the synthesized + audio content. + sample_rate_hertz (int): + The synthesis sample rate (in hertz) for this + audio. If not provided, then the synthesizer + will use the default sample rate based on the + audio encoding. If this is different from the + voice's natural sample rate, then the + synthesizer will honor this request by + converting to the desired sample rate (which + might result in worse audio quality). + synthesize_speech_config (google.cloud.dialogflow_v2.types.SynthesizeSpeechConfig): + Configuration of how speech should be + synthesized. + """ + + audio_encoding = proto.Field( + proto.ENUM, + number=1, + enum='OutputAudioEncoding', + ) + sample_rate_hertz = proto.Field( + proto.INT32, + number=2, + ) + synthesize_speech_config = proto.Field( + proto.MESSAGE, + number=3, + message='SynthesizeSpeechConfig', + ) + + +class SpeechToTextConfig(proto.Message): + r"""Configures speech transcription for + [ConversationProfile][google.cloud.dialogflow.v2.ConversationProfile]. + + Attributes: + speech_model_variant (google.cloud.dialogflow_v2.types.SpeechModelVariant): + The speech model used in speech to text. + ``SPEECH_MODEL_VARIANT_UNSPECIFIED``, ``USE_BEST_AVAILABLE`` + will be treated as ``USE_ENHANCED``. It can be overridden in + [AnalyzeContentRequest][google.cloud.dialogflow.v2.AnalyzeContentRequest] + and + [StreamingAnalyzeContentRequest][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest] + request. If enhanced model variant is specified and an + enhanced version of the specified model for the language + does not exist, then it would emit an error. + """ + + speech_model_variant = proto.Field( + proto.ENUM, + number=1, + enum='SpeechModelVariant', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/context.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/context.py new file mode 100644 index 000000000..066ef0f13 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/context.py @@ -0,0 +1,298 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + 'Context', + 'ListContextsRequest', + 'ListContextsResponse', + 'GetContextRequest', + 'CreateContextRequest', + 'UpdateContextRequest', + 'DeleteContextRequest', + 'DeleteAllContextsRequest', + }, +) + + +class Context(proto.Message): + r"""Dialogflow contexts are similar to natural language context. If a + person says to you "they are orange", you need context in order to + understand what "they" is referring to. Similarly, for Dialogflow to + handle an end-user expression like that, it needs to be provided + with context in order to correctly match an intent. + + Using contexts, you can control the flow of a conversation. You can + configure contexts for an intent by setting input and output + contexts, which are identified by string names. When an intent is + matched, any configured output contexts for that intent become + active. While any contexts are active, Dialogflow is more likely to + match intents that are configured with input contexts that + correspond to the currently active contexts. + + For more information about context, see the `Contexts + guide `__. + + Attributes: + name (str): + Required. The unique identifier of the context. Format: + ``projects//agent/sessions//contexts/``, + or + ``projects//agent/environments//users//sessions//contexts/``. + + The ``Context ID`` is always converted to lowercase, may + only contain characters in a-zA-Z0-9_-% and may be at most + 250 bytes long. + + If ``Environment ID`` is not specified, we assume default + 'draft' environment. If ``User ID`` is not specified, we + assume default '-' user. + + The following context names are reserved for internal use by + Dialogflow. You should not use these contexts or create + contexts with these names: + + - ``__system_counters__`` + - ``*_id_dialog_context`` + - ``*_dialog_params_size`` + lifespan_count (int): + Optional. The number of conversational query requests after + which the context expires. The default is ``0``. If set to + ``0``, the context expires immediately. Contexts expire + automatically after 20 minutes if there are no matching + queries. + parameters (google.protobuf.struct_pb2.Struct): + Optional. The collection of parameters + associated with this context. + Depending on your protocol or client library + language, this is a map, associative array, + symbol table, dictionary, or JSON object + composed of a collection of (MapKey, MapValue) + pairs: + - MapKey type: string + - MapKey value: parameter name + - MapValue type: + - If parameter's entity type is a + composite entity: map - Else: depending on + parameter value type, could be one of string, + number, boolean, null, list or map + - MapValue value: + - If parameter's entity type is a + composite entity: map from composite + entity property names to property values - + Else: parameter value + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + lifespan_count = proto.Field( + proto.INT32, + number=2, + ) + parameters = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + + +class ListContextsRequest(proto.Message): + r"""The request message for + [Contexts.ListContexts][google.cloud.dialogflow.v2.Contexts.ListContexts]. + + Attributes: + parent (str): + Required. The session to list all contexts from. Format: + ``projects//agent/sessions/`` or + ``projects//agent/environments//users//sessions/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. If ``User ID`` is not specified, we + assume default '-' user. + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListContextsResponse(proto.Message): + r"""The response message for + [Contexts.ListContexts][google.cloud.dialogflow.v2.Contexts.ListContexts]. + + Attributes: + contexts (Sequence[google.cloud.dialogflow_v2.types.Context]): + The list of contexts. There will be a maximum number of + items returned based on the page_size field in the request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + contexts = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Context', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetContextRequest(proto.Message): + r"""The request message for + [Contexts.GetContext][google.cloud.dialogflow.v2.Contexts.GetContext]. + + Attributes: + name (str): + Required. The name of the context. Format: + ``projects//agent/sessions//contexts/`` + or + ``projects//agent/environments//users//sessions//contexts/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. If ``User ID`` is not specified, we + assume default '-' user. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateContextRequest(proto.Message): + r"""The request message for + [Contexts.CreateContext][google.cloud.dialogflow.v2.Contexts.CreateContext]. + + Attributes: + parent (str): + Required. The session to create a context for. Format: + ``projects//agent/sessions/`` or + ``projects//agent/environments//users//sessions/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. If ``User ID`` is not specified, we + assume default '-' user. + context (google.cloud.dialogflow_v2.types.Context): + Required. The context to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + context = proto.Field( + proto.MESSAGE, + number=2, + message='Context', + ) + + +class UpdateContextRequest(proto.Message): + r"""The request message for + [Contexts.UpdateContext][google.cloud.dialogflow.v2.Contexts.UpdateContext]. + + Attributes: + context (google.cloud.dialogflow_v2.types.Context): + Required. The context to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which fields + get updated. + """ + + context = proto.Field( + proto.MESSAGE, + number=1, + message='Context', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteContextRequest(proto.Message): + r"""The request message for + [Contexts.DeleteContext][google.cloud.dialogflow.v2.Contexts.DeleteContext]. + + Attributes: + name (str): + Required. The name of the context to delete. Format: + ``projects//agent/sessions//contexts/`` + or + ``projects//agent/environments//users//sessions//contexts/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. If ``User ID`` is not specified, we + assume default '-' user. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteAllContextsRequest(proto.Message): + r"""The request message for + [Contexts.DeleteAllContexts][google.cloud.dialogflow.v2.Contexts.DeleteAllContexts]. + + Attributes: + parent (str): + Required. The name of the session to delete all contexts + from. Format: + ``projects//agent/sessions/`` or + ``projects//agent/environments//users//sessions/``. + If ``Environment ID`` is not specified we assume default + 'draft' environment. If ``User ID`` is not specified, we + assume default '-' user. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation.py new file mode 100644 index 000000000..30727db67 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation.py @@ -0,0 +1,390 @@ +# -*- 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.dialogflow_v2.types import participant +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + 'Conversation', + 'CreateConversationRequest', + 'ListConversationsRequest', + 'ListConversationsResponse', + 'GetConversationRequest', + 'CompleteConversationRequest', + 'ListMessagesRequest', + 'ListMessagesResponse', + 'ConversationPhoneNumber', + }, +) + + +class Conversation(proto.Message): + r"""Represents a conversation. + A conversation is an interaction between an agent, including + live agents and Dialogflow agents, and a support customer. + Conversations can include phone calls and text-based chat + sessions. + + Attributes: + name (str): + Output only. The unique identifier of this conversation. + Format: + ``projects//locations//conversations/``. + lifecycle_state (google.cloud.dialogflow_v2.types.Conversation.LifecycleState): + Output only. The current state of the + Conversation. + conversation_profile (str): + Required. The Conversation Profile to be used to configure + this Conversation. This field cannot be updated. Format: + ``projects//locations//conversationProfiles/``. + phone_number (google.cloud.dialogflow_v2.types.ConversationPhoneNumber): + Output only. It will not be empty if the + conversation is to be connected over telephony. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the conversation was + started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the conversation was + finished. + conversation_stage (google.cloud.dialogflow_v2.types.Conversation.ConversationStage): + The stage of a conversation. It indicates whether the + virtual agent or a human agent is handling the conversation. + + If the conversation is created with the conversation profile + that has Dialogflow config set, defaults to + [ConversationStage.VIRTUAL_AGENT_STAGE][google.cloud.dialogflow.v2.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE]; + Otherwise, defaults to + [ConversationStage.HUMAN_ASSIST_STAGE][google.cloud.dialogflow.v2.Conversation.ConversationStage.HUMAN_ASSIST_STAGE]. + + If the conversation is created with the conversation profile + that has Dialogflow config set but explicitly sets + conversation_stage to + [ConversationStage.HUMAN_ASSIST_STAGE][google.cloud.dialogflow.v2.Conversation.ConversationStage.HUMAN_ASSIST_STAGE], + it skips + [ConversationStage.VIRTUAL_AGENT_STAGE][google.cloud.dialogflow.v2.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE] + stage and directly goes to + [ConversationStage.HUMAN_ASSIST_STAGE][google.cloud.dialogflow.v2.Conversation.ConversationStage.HUMAN_ASSIST_STAGE]. + """ + class LifecycleState(proto.Enum): + r"""Enumeration of the completion status of the conversation.""" + LIFECYCLE_STATE_UNSPECIFIED = 0 + IN_PROGRESS = 1 + COMPLETED = 2 + + class ConversationStage(proto.Enum): + r"""Enumeration of the different conversation stages a + conversation can be in. Reference: + https://cloud.google.com/dialogflow/priv/docs/contact- + center/basics#stages + """ + CONVERSATION_STAGE_UNSPECIFIED = 0 + VIRTUAL_AGENT_STAGE = 1 + HUMAN_ASSIST_STAGE = 2 + + name = proto.Field( + proto.STRING, + number=1, + ) + lifecycle_state = proto.Field( + proto.ENUM, + number=2, + enum=LifecycleState, + ) + conversation_profile = proto.Field( + proto.STRING, + number=3, + ) + phone_number = proto.Field( + proto.MESSAGE, + number=4, + message='ConversationPhoneNumber', + ) + start_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + conversation_stage = proto.Field( + proto.ENUM, + number=7, + enum=ConversationStage, + ) + + +class CreateConversationRequest(proto.Message): + r"""The request message for + [Conversations.CreateConversation][google.cloud.dialogflow.v2.Conversations.CreateConversation]. + + Attributes: + parent (str): + Required. Resource identifier of the project creating the + conversation. Format: + ``projects//locations/``. + conversation (google.cloud.dialogflow_v2.types.Conversation): + Required. The conversation to create. + conversation_id (str): + Optional. Identifier of the conversation. Generally it's + auto generated by Google. Only set it if you cannot wait for + the response to return a auto-generated one to you. + + The conversation ID must be compliant with the regression + fomula "[a-zA-Z][a-zA-Z0-9_-]*" with the characters length + in range of [3,64]. If the field is provided, the caller is + resposible for + + 1. the uniqueness of the ID, otherwise the request will be + rejected. + 2. the consistency for whether to use custom ID or not under + a project to better ensure uniqueness. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + conversation = proto.Field( + proto.MESSAGE, + number=2, + message='Conversation', + ) + conversation_id = proto.Field( + proto.STRING, + number=3, + ) + + +class ListConversationsRequest(proto.Message): + r"""The request message for + [Conversations.ListConversations][google.cloud.dialogflow.v2.Conversations.ListConversations]. + + Attributes: + parent (str): + Required. The project from which to list all conversation. + Format: ``projects//locations/``. + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + filter (str): + A filter expression that filters conversations listed in the + response. In general, the expression must specify the field + name, a comparison operator, and the value to use for + filtering: + + .. raw:: html + +
    +
  • The value must be a string, a number, or a boolean.
  • +
  • The comparison operator must be either `=`,`!=`, `>`, or `<`.
  • +
  • To filter on multiple expressions, separate the + expressions with `AND` or `OR` (omitting both implies `AND`).
  • +
  • For clarity, expressions can be enclosed in parentheses.
  • +
+ Only `lifecycle_state` can be filtered on in this way. For example, + the following expression only returns `COMPLETED` conversations: + + ``lifecycle_state = "COMPLETED"`` + + For more information about filtering, see `API + Filtering `__. + """ + + 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 ListConversationsResponse(proto.Message): + r"""The response message for + [Conversations.ListConversations][google.cloud.dialogflow.v2.Conversations.ListConversations]. + + Attributes: + conversations (Sequence[google.cloud.dialogflow_v2.types.Conversation]): + The list of conversations. There will be a maximum number of + items returned based on the page_size field in the request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + conversations = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Conversation', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetConversationRequest(proto.Message): + r"""The request message for + [Conversations.GetConversation][google.cloud.dialogflow.v2.Conversations.GetConversation]. + + Attributes: + name (str): + Required. The name of the conversation. Format: + ``projects//locations//conversations/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CompleteConversationRequest(proto.Message): + r"""The request message for + [Conversations.CompleteConversation][google.cloud.dialogflow.v2.Conversations.CompleteConversation]. + + Attributes: + name (str): + Required. Resource identifier of the conversation to close. + Format: + ``projects//locations//conversations/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListMessagesRequest(proto.Message): + r"""The request message for + [Conversations.ListMessages][google.cloud.dialogflow.v2.Conversations.ListMessages]. + + Attributes: + parent (str): + Required. The name of the conversation to list messages for. + Format: + ``projects//locations//conversations/`` + filter (str): + Optional. Filter on message fields. Currently predicates on + ``create_time`` and ``create_time_epoch_microseconds`` are + supported. ``create_time`` only support milliseconds + accuracy. E.g., + ``create_time_epoch_microseconds > 1551790877964485`` or + ``create_time > 2017-01-15T01:30:15.01Z``. + + For more information about filtering, see `API + Filtering `__. + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListMessagesResponse(proto.Message): + r"""The response message for + [Conversations.ListMessages][google.cloud.dialogflow.v2.Conversations.ListMessages]. + + Attributes: + messages (Sequence[google.cloud.dialogflow_v2.types.Message]): + The list of messages. There will be a maximum number of + items returned based on the page_size field in the request. + ``messages`` is sorted by ``create_time`` in descending + order. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + messages = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=participant.Message, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class ConversationPhoneNumber(proto.Message): + r"""Represents a phone number for telephony integration. It + allows for connecting a particular conversation over telephony. + + Attributes: + phone_number (str): + Output only. The phone number to connect to + this conversation. + """ + + phone_number = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_event.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_event.py new file mode 100644 index 000000000..7d447aa15 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_event.py @@ -0,0 +1,84 @@ +# -*- 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.dialogflow_v2.types import participant +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + 'ConversationEvent', + }, +) + + +class ConversationEvent(proto.Message): + r"""Represents a notification sent to Pub/Sub subscribers for + conversation lifecycle events. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + conversation (str): + The unique identifier of the conversation this notification + refers to. Format: + ``projects//conversations/``. + type_ (google.cloud.dialogflow_v2.types.ConversationEvent.Type): + The type of the event that this notification + refers to. + error_status (google.rpc.status_pb2.Status): + More detailed information about an error. Only set for type + UNRECOVERABLE_ERROR_IN_PHONE_CALL. + new_message_payload (google.cloud.dialogflow_v2.types.Message): + Payload of NEW_MESSAGE event. + + This field is a member of `oneof`_ ``payload``. + """ + class Type(proto.Enum): + r"""Enumeration of the types of events available.""" + TYPE_UNSPECIFIED = 0 + CONVERSATION_STARTED = 1 + CONVERSATION_FINISHED = 2 + HUMAN_INTERVENTION_NEEDED = 3 + NEW_MESSAGE = 5 + UNRECOVERABLE_ERROR = 4 + + conversation = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.ENUM, + number=2, + enum=Type, + ) + error_status = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + new_message_payload = proto.Field( + proto.MESSAGE, + number=4, + oneof='payload', + message=participant.Message, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_profile.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_profile.py new file mode 100644 index 000000000..934419db7 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_profile.py @@ -0,0 +1,892 @@ +# -*- 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.dialogflow_v2.types import audio_config +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + 'ConversationProfile', + 'ListConversationProfilesRequest', + 'ListConversationProfilesResponse', + 'GetConversationProfileRequest', + 'CreateConversationProfileRequest', + 'UpdateConversationProfileRequest', + 'DeleteConversationProfileRequest', + 'AutomatedAgentConfig', + 'HumanAgentAssistantConfig', + 'HumanAgentHandoffConfig', + 'NotificationConfig', + 'LoggingConfig', + 'SuggestionFeature', + }, +) + + +class ConversationProfile(proto.Message): + r"""Defines the services to connect to incoming Dialogflow + conversations. + + Attributes: + name (str): + The unique identifier of this conversation profile. Format: + ``projects//locations//conversationProfiles/``. + display_name (str): + Required. Human readable name for this + profile. Max length 1024 bytes. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Create time of the conversation + profile. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Update time of the conversation + profile. + automated_agent_config (google.cloud.dialogflow_v2.types.AutomatedAgentConfig): + Configuration for an automated agent to use + with this profile. + human_agent_assistant_config (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig): + Configuration for agent assistance to use + with this profile. + human_agent_handoff_config (google.cloud.dialogflow_v2.types.HumanAgentHandoffConfig): + Configuration for connecting to a live agent. + Currently, this feature is not general + available, please contact Google to get access. + notification_config (google.cloud.dialogflow_v2.types.NotificationConfig): + Configuration for publishing conversation + lifecycle events. + logging_config (google.cloud.dialogflow_v2.types.LoggingConfig): + Configuration for logging conversation + lifecycle events. + new_message_event_notification_config (google.cloud.dialogflow_v2.types.NotificationConfig): + Configuration for publishing new message events. Event will + be sent in format of + [ConversationEvent][google.cloud.dialogflow.v2.ConversationEvent] + stt_config (google.cloud.dialogflow_v2.types.SpeechToTextConfig): + Settings for speech transcription. + language_code (str): + Language code for the conversation profile. If not + specified, the language is en-US. Language at + ConversationProfile should be set for all non en-US + languages. This should be a + `BCP-47 `__ + language tag. Example: "en-US". + time_zone (str): + The time zone of this conversational profile from the `time + zone database `__, e.g., + America/New_York, Europe/Paris. Defaults to + America/New_York. + security_settings (str): + Name of the CX SecuritySettings reference for the agent. + Format: + ``projects//locations//securitySettings/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + create_time = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=12, + message=timestamp_pb2.Timestamp, + ) + automated_agent_config = proto.Field( + proto.MESSAGE, + number=3, + message='AutomatedAgentConfig', + ) + human_agent_assistant_config = proto.Field( + proto.MESSAGE, + number=4, + message='HumanAgentAssistantConfig', + ) + human_agent_handoff_config = proto.Field( + proto.MESSAGE, + number=5, + message='HumanAgentHandoffConfig', + ) + notification_config = proto.Field( + proto.MESSAGE, + number=6, + message='NotificationConfig', + ) + logging_config = proto.Field( + proto.MESSAGE, + number=7, + message='LoggingConfig', + ) + new_message_event_notification_config = proto.Field( + proto.MESSAGE, + number=8, + message='NotificationConfig', + ) + stt_config = proto.Field( + proto.MESSAGE, + number=9, + message=audio_config.SpeechToTextConfig, + ) + language_code = proto.Field( + proto.STRING, + number=10, + ) + time_zone = proto.Field( + proto.STRING, + number=14, + ) + security_settings = proto.Field( + proto.STRING, + number=13, + ) + + +class ListConversationProfilesRequest(proto.Message): + r"""The request message for + [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2.ConversationProfiles.ListConversationProfiles]. + + Attributes: + parent (str): + Required. The project to list all conversation profiles + from. Format: + ``projects//locations/``. + page_size (int): + The maximum number of items to return in a + single page. By default 100 and at most 1000. + page_token (str): + The next_page_token value returned from a previous list + request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListConversationProfilesResponse(proto.Message): + r"""The response message for + [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2.ConversationProfiles.ListConversationProfiles]. + + Attributes: + conversation_profiles (Sequence[google.cloud.dialogflow_v2.types.ConversationProfile]): + The list of project conversation profiles. There is a + maximum number of items returned based on the page_size + field in the request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + conversation_profiles = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ConversationProfile', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetConversationProfileRequest(proto.Message): + r"""The request message for + [ConversationProfiles.GetConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.GetConversationProfile]. + + Attributes: + name (str): + Required. The resource name of the conversation profile. + Format: + ``projects//locations//conversationProfiles/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateConversationProfileRequest(proto.Message): + r"""The request message for + [ConversationProfiles.CreateConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.CreateConversationProfile]. + + Attributes: + parent (str): + Required. The project to create a conversation profile for. + Format: ``projects//locations/``. + conversation_profile (google.cloud.dialogflow_v2.types.ConversationProfile): + Required. The conversation profile to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + conversation_profile = proto.Field( + proto.MESSAGE, + number=2, + message='ConversationProfile', + ) + + +class UpdateConversationProfileRequest(proto.Message): + r"""The request message for + [ConversationProfiles.UpdateConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.UpdateConversationProfile]. + + Attributes: + conversation_profile (google.cloud.dialogflow_v2.types.ConversationProfile): + Required. The conversation profile to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields to + update. + """ + + conversation_profile = proto.Field( + proto.MESSAGE, + number=1, + message='ConversationProfile', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteConversationProfileRequest(proto.Message): + r"""The request message for + [ConversationProfiles.DeleteConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.DeleteConversationProfile]. + + This operation fails if the conversation profile is still referenced + from a phone number. + + Attributes: + name (str): + Required. The name of the conversation profile to delete. + Format: + ``projects//locations//conversationProfiles/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class AutomatedAgentConfig(proto.Message): + r"""Defines the Automated Agent to connect to a conversation. + + Attributes: + agent (str): + Required. ID of the Dialogflow agent environment to use. + + This project needs to either be the same project as the + conversation or you need to grant + ``service-@gcp-sa-dialogflow.iam.gserviceaccount.com`` + the ``Dialogflow API Service Agent`` role in this project. + + - For ES agents, use format: + ``projects//locations//agent/environments/``. + If environment is not specified, the default ``draft`` + environment is used. Refer to + `DetectIntentRequest `__ + for more details. + + - For CX agents, use format + ``projects//locations//agents//environments/``. + If environment is not specified, the default ``draft`` + environment is used. + """ + + agent = proto.Field( + proto.STRING, + number=1, + ) + + +class HumanAgentAssistantConfig(proto.Message): + r"""Defines the Human Agent Assist to connect to a conversation. + + Attributes: + notification_config (google.cloud.dialogflow_v2.types.NotificationConfig): + Pub/Sub topic on which to publish new agent + assistant events. + human_agent_suggestion_config (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionConfig): + Configuration for agent assistance of human + agent participant. + end_user_suggestion_config (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionConfig): + Configuration for agent assistance of end + user participant. + Currently, this feature is not general + available, please contact Google to get access. + message_analysis_config (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.MessageAnalysisConfig): + Configuration for message analysis. + """ + + class SuggestionTriggerSettings(proto.Message): + r"""Settings of suggestion trigger. + + Attributes: + no_smalltalk (bool): + Do not trigger if last utterance is small + talk. + only_end_user (bool): + Only trigger suggestion if participant role of last + utterance is END_USER. + """ + + no_smalltalk = proto.Field( + proto.BOOL, + number=1, + ) + only_end_user = proto.Field( + proto.BOOL, + number=2, + ) + + class SuggestionFeatureConfig(proto.Message): + r"""Config for suggestion features. + + Attributes: + suggestion_feature (google.cloud.dialogflow_v2.types.SuggestionFeature): + The suggestion feature. + enable_event_based_suggestion (bool): + Automatically iterates all participants and tries to compile + suggestions. + + Supported features: ARTICLE_SUGGESTION, FAQ, + DIALOGFLOW_ASSIST. + suggestion_trigger_settings (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionTriggerSettings): + Settings of suggestion trigger. + + Currently, only ARTICLE_SUGGESTION and FAQ will use this + field. + query_config (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionQueryConfig): + Configs of query. + conversation_model_config (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.ConversationModelConfig): + Configs of custom conversation model. + """ + + suggestion_feature = proto.Field( + proto.MESSAGE, + number=5, + message='SuggestionFeature', + ) + enable_event_based_suggestion = proto.Field( + proto.BOOL, + number=3, + ) + suggestion_trigger_settings = proto.Field( + proto.MESSAGE, + number=10, + message='HumanAgentAssistantConfig.SuggestionTriggerSettings', + ) + query_config = proto.Field( + proto.MESSAGE, + number=6, + message='HumanAgentAssistantConfig.SuggestionQueryConfig', + ) + conversation_model_config = proto.Field( + proto.MESSAGE, + number=7, + message='HumanAgentAssistantConfig.ConversationModelConfig', + ) + + class SuggestionConfig(proto.Message): + r"""Detail human agent assistant config. + + Attributes: + feature_configs (Sequence[google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionFeatureConfig]): + Configuration of different suggestion + features. One feature can have only one config. + group_suggestion_responses (bool): + If ``group_suggestion_responses`` is false, and there are + multiple ``feature_configs`` in ``event based suggestion`` + or StreamingAnalyzeContent, we will try to deliver + suggestions to customers as soon as we get new suggestion. + Different type of suggestions based on the same context will + be in separate Pub/Sub event or + ``StreamingAnalyzeContentResponse``. + + If ``group_suggestion_responses`` set to true. All the + suggestions to the same participant based on the same + context will be grouped into a single Pub/Sub event or + StreamingAnalyzeContentResponse. + """ + + feature_configs = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='HumanAgentAssistantConfig.SuggestionFeatureConfig', + ) + group_suggestion_responses = proto.Field( + proto.BOOL, + number=3, + ) + + class SuggestionQueryConfig(proto.Message): + r"""Config for suggestion query. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + knowledge_base_query_source (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionQueryConfig.KnowledgeBaseQuerySource): + Query from knowledgebase. It is used by: ARTICLE_SUGGESTION, + FAQ. + + This field is a member of `oneof`_ ``query_source``. + document_query_source (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionQueryConfig.DocumentQuerySource): + Query from knowledge base document. It is used by: + SMART_REPLY, SMART_COMPOSE. + + This field is a member of `oneof`_ ``query_source``. + dialogflow_query_source (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionQueryConfig.DialogflowQuerySource): + Query from Dialogflow agent. It is used by + DIALOGFLOW_ASSIST. + + This field is a member of `oneof`_ ``query_source``. + max_results (int): + Maximum number of results to return. + Currently, if unset, defaults to 10. And the max + number is 20. + confidence_threshold (float): + Confidence threshold of query result. + + Agent Assist gives each suggestion a score in the range + [0.0, 1.0], based on the relevance between the suggestion + and the current conversation context. A score of 0.0 has no + relevance, while a score of 1.0 has high relevance. Only + suggestions with a score greater than or equal to the value + of this field are included in the results. + + For a baseline model (the default), the recommended value is + in the range [0.05, 0.1]. + + For a custom model, there is no recommended value. Tune this + value by starting from a very low value and slowly + increasing until you have desired results. + + If this field is not set, it defaults to 0.0, which means + that all suggestions are returned. + + Supported features: ARTICLE_SUGGESTION, FAQ, SMART_REPLY, + SMART_COMPOSE. + context_filter_settings (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionQueryConfig.ContextFilterSettings): + Determines how recent conversation context is + filtered when generating suggestions. If + unspecified, no messages will be dropped. + """ + + class KnowledgeBaseQuerySource(proto.Message): + r"""Knowledge base source settings. + + Supported features: ARTICLE_SUGGESTION, FAQ. + + Attributes: + knowledge_bases (Sequence[str]): + Required. Knowledge bases to query. Format: + ``projects//locations//knowledgeBases/``. + Currently, at most 5 knowledge bases are supported. + """ + + knowledge_bases = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class DocumentQuerySource(proto.Message): + r"""Document source settings. + + Supported features: SMART_REPLY, SMART_COMPOSE. + + Attributes: + documents (Sequence[str]): + Required. Knowledge documents to query from. Format: + ``projects//locations//knowledgeBases//documents/``. + Currently, at most 5 documents are supported. + """ + + documents = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class DialogflowQuerySource(proto.Message): + r"""Dialogflow source setting. + + Supported feature: DIALOGFLOW_ASSIST. + + Attributes: + agent (str): + Required. The name of a Dialogflow virtual agent used for + end user side intent detection and suggestion. Format: + ``projects//locations//agent``. + When multiple agents are allowed in the same Dialogflow + project. + """ + + agent = proto.Field( + proto.STRING, + number=1, + ) + + class ContextFilterSettings(proto.Message): + r"""Settings that determine how to filter recent conversation + context when generating suggestions. + + Attributes: + drop_handoff_messages (bool): + If set to true, the last message from virtual + agent (hand off message) and the message before + it (trigger message of hand off) are dropped. + drop_virtual_agent_messages (bool): + If set to true, all messages from virtual + agent are dropped. + drop_ivr_messages (bool): + If set to true, all messages from ivr stage + are dropped. + """ + + drop_handoff_messages = proto.Field( + proto.BOOL, + number=1, + ) + drop_virtual_agent_messages = proto.Field( + proto.BOOL, + number=2, + ) + drop_ivr_messages = proto.Field( + proto.BOOL, + number=3, + ) + + knowledge_base_query_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='query_source', + message='HumanAgentAssistantConfig.SuggestionQueryConfig.KnowledgeBaseQuerySource', + ) + document_query_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='query_source', + message='HumanAgentAssistantConfig.SuggestionQueryConfig.DocumentQuerySource', + ) + dialogflow_query_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='query_source', + message='HumanAgentAssistantConfig.SuggestionQueryConfig.DialogflowQuerySource', + ) + max_results = proto.Field( + proto.INT32, + number=4, + ) + confidence_threshold = proto.Field( + proto.FLOAT, + number=5, + ) + context_filter_settings = proto.Field( + proto.MESSAGE, + number=7, + message='HumanAgentAssistantConfig.SuggestionQueryConfig.ContextFilterSettings', + ) + + class ConversationModelConfig(proto.Message): + r"""Custom conversation models used in agent assist feature. + + Supported feature: ARTICLE_SUGGESTION, SMART_COMPOSE, SMART_REPLY. + + Attributes: + model (str): + Conversation model resource name. Format: + ``projects//conversationModels/``. + """ + + model = proto.Field( + proto.STRING, + number=1, + ) + + class MessageAnalysisConfig(proto.Message): + r"""Configuration for analyses to run on each conversation + message. + + Attributes: + enable_entity_extraction (bool): + Enable entity extraction in conversation messages on `agent + assist + stage `__. + If unspecified, defaults to false. + + Currently, this feature is not general available, please + contact Google to get access. + enable_sentiment_analysis (bool): + Enable sentiment analysis in conversation messages on `agent + assist + stage `__. + If unspecified, defaults to false. Sentiment analysis + inspects user input and identifies the prevailing subjective + opinion, especially to determine a user's attitude as + positive, negative, or neutral: + https://cloud.google.com/natural-language/docs/basics#sentiment_analysis + For + [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent] + method, result will be in + [StreamingAnalyzeContentResponse.message.SentimentAnalysisResult][google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse.message]. + For + [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent] + method, result will be in + [AnalyzeContentResponse.message.SentimentAnalysisResult][google.cloud.dialogflow.v2.AnalyzeContentResponse.message] + For + [Conversations.ListMessages][google.cloud.dialogflow.v2.Conversations.ListMessages] + method, result will be in + [ListMessagesResponse.messages.SentimentAnalysisResult][google.cloud.dialogflow.v2.ListMessagesResponse.messages] + If Pub/Sub notification is configured, result will be in + [ConversationEvent.new_message_payload.SentimentAnalysisResult][google.cloud.dialogflow.v2.ConversationEvent.new_message_payload]. + """ + + enable_entity_extraction = proto.Field( + proto.BOOL, + number=2, + ) + enable_sentiment_analysis = proto.Field( + proto.BOOL, + number=3, + ) + + notification_config = proto.Field( + proto.MESSAGE, + number=2, + message='NotificationConfig', + ) + human_agent_suggestion_config = proto.Field( + proto.MESSAGE, + number=3, + message=SuggestionConfig, + ) + end_user_suggestion_config = proto.Field( + proto.MESSAGE, + number=4, + message=SuggestionConfig, + ) + message_analysis_config = proto.Field( + proto.MESSAGE, + number=5, + message=MessageAnalysisConfig, + ) + + +class HumanAgentHandoffConfig(proto.Message): + r"""Defines the hand off to a live agent, typically on which + external agent service provider to connect to a conversation. + Currently, this feature is not general available, please contact + Google to get access. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + live_person_config (google.cloud.dialogflow_v2.types.HumanAgentHandoffConfig.LivePersonConfig): + Uses LivePerson (https://www.liveperson.com). + + This field is a member of `oneof`_ ``agent_service``. + salesforce_live_agent_config (google.cloud.dialogflow_v2.types.HumanAgentHandoffConfig.SalesforceLiveAgentConfig): + Uses Salesforce Live Agent. + + This field is a member of `oneof`_ ``agent_service``. + """ + + class LivePersonConfig(proto.Message): + r"""Configuration specific to LivePerson + (https://www.liveperson.com). + + Attributes: + account_number (str): + Required. Account number of the LivePerson + account to connect. This is the account number + you input at the login page. + """ + + account_number = proto.Field( + proto.STRING, + number=1, + ) + + class SalesforceLiveAgentConfig(proto.Message): + r"""Configuration specific to Salesforce Live Agent. + + Attributes: + organization_id (str): + Required. The organization ID of the + Salesforce account. + deployment_id (str): + Required. Live Agent deployment ID. + button_id (str): + Required. Live Agent chat button ID. + endpoint_domain (str): + Required. Domain of the Live Agent endpoint for this agent. + You can find the endpoint URL in the ``Live Agent settings`` + page. For example if URL has the form + https://d.la4-c2-phx.salesforceliveagent.com/..., you should + fill in d.la4-c2-phx.salesforceliveagent.com. + """ + + organization_id = proto.Field( + proto.STRING, + number=1, + ) + deployment_id = proto.Field( + proto.STRING, + number=2, + ) + button_id = proto.Field( + proto.STRING, + number=3, + ) + endpoint_domain = proto.Field( + proto.STRING, + number=4, + ) + + live_person_config = proto.Field( + proto.MESSAGE, + number=1, + oneof='agent_service', + message=LivePersonConfig, + ) + salesforce_live_agent_config = proto.Field( + proto.MESSAGE, + number=2, + oneof='agent_service', + message=SalesforceLiveAgentConfig, + ) + + +class NotificationConfig(proto.Message): + r"""Defines notification behavior. + + Attributes: + topic (str): + Name of the Pub/Sub topic to publish conversation events + like + [CONVERSATION_STARTED][google.cloud.dialogflow.v2.ConversationEvent.Type.CONVERSATION_STARTED] + as serialized + [ConversationEvent][google.cloud.dialogflow.v2.ConversationEvent] + protos. + + Notification works for phone calls, if this topic either is + in the same project as the conversation or you grant + ``service-@gcp-sa-dialogflow.iam.gserviceaccount.com`` + the ``Dialogflow Service Agent`` role in the topic project. + + Format: + ``projects//locations//topics/``. + message_format (google.cloud.dialogflow_v2.types.NotificationConfig.MessageFormat): + Format of message. + """ + class MessageFormat(proto.Enum): + r"""Format of cloud pub/sub message.""" + MESSAGE_FORMAT_UNSPECIFIED = 0 + PROTO = 1 + JSON = 2 + + topic = proto.Field( + proto.STRING, + number=1, + ) + message_format = proto.Field( + proto.ENUM, + number=2, + enum=MessageFormat, + ) + + +class LoggingConfig(proto.Message): + r"""Defines logging behavior for conversation lifecycle events. + + Attributes: + enable_stackdriver_logging (bool): + Whether to log conversation events like + [CONVERSATION_STARTED][google.cloud.dialogflow.v2.ConversationEvent.Type.CONVERSATION_STARTED] + to Stackdriver in the conversation project as JSON format + [ConversationEvent][google.cloud.dialogflow.v2.ConversationEvent] + protos. + """ + + enable_stackdriver_logging = proto.Field( + proto.BOOL, + number=3, + ) + + +class SuggestionFeature(proto.Message): + r"""The type of Human Agent Assistant API suggestion to perform, and the + maximum number of results to return for that type. Multiple + ``Feature`` objects can be specified in the ``features`` list. + + Attributes: + type_ (google.cloud.dialogflow_v2.types.SuggestionFeature.Type): + Type of Human Agent Assistant API feature to + request. + """ + class Type(proto.Enum): + r"""Defines the type of Human Agent Assistant feature.""" + TYPE_UNSPECIFIED = 0 + ARTICLE_SUGGESTION = 1 + FAQ = 2 + SMART_REPLY = 3 + + type_ = proto.Field( + proto.ENUM, + number=1, + enum=Type, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/document.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/document.py new file mode 100644 index 000000000..d584a4276 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/document.py @@ -0,0 +1,479 @@ +# -*- 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.dialogflow_v2.types import gcs +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + 'Document', + 'GetDocumentRequest', + 'ListDocumentsRequest', + 'ListDocumentsResponse', + 'CreateDocumentRequest', + 'DeleteDocumentRequest', + 'UpdateDocumentRequest', + 'ReloadDocumentRequest', + 'ExportDocumentRequest', + 'KnowledgeOperationMetadata', + }, +) + + +class Document(proto.Message): + r"""A knowledge document to be used by a + [KnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBase]. + + For more information, see the `knowledge base + guide `__. + + Note: The ``projects.agent.knowledgeBases.documents`` resource is + deprecated; only use ``projects.knowledgeBases.documents``. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Optional. The document resource name. The name must be empty + when creating a document. Format: + ``projects//locations//knowledgeBases//documents/``. + display_name (str): + Required. The display name of the document. + The name must be 1024 bytes or less; otherwise, + the creation request fails. + mime_type (str): + Required. The MIME type of this document. + knowledge_types (Sequence[google.cloud.dialogflow_v2.types.Document.KnowledgeType]): + Required. The knowledge type of document + content. + content_uri (str): + The URI where the file content is located. + + For documents stored in Google Cloud Storage, these URIs + must have the form ``gs:///``. + + NOTE: External URLs must correspond to public webpages, + i.e., they must be indexed by Google Search. In particular, + URLs for showing documents in Google Cloud Storage (i.e. the + URL in your browser) are not supported. Instead use the + ``gs://`` format URI described above. + + This field is a member of `oneof`_ ``source``. + raw_content (bytes): + The raw content of the document. This field is only + permitted for EXTRACTIVE_QA and FAQ knowledge types. + + This field is a member of `oneof`_ ``source``. + enable_auto_reload (bool): + Optional. If true, we try to automatically reload the + document every day (at a time picked by the system). If + false or unspecified, we don't try to automatically reload + the document. + + Currently you can only enable automatic reload for documents + sourced from a public url, see ``source`` field for the + source types. + + Reload status can be tracked in ``latest_reload_status``. If + a reload fails, we will keep the document unchanged. + + If a reload fails with internal errors, the system will try + to reload the document on the next day. If a reload fails + with non-retriable errors (e.g. PERMISION_DENIED), the + system will not try to reload the document anymore. You need + to manually reload the document successfully by calling + ``ReloadDocument`` and clear the errors. + latest_reload_status (google.cloud.dialogflow_v2.types.Document.ReloadStatus): + Output only. The time and status of the + latest reload. This reload may have been + triggered automatically or manually and may not + have succeeded. + metadata (Sequence[google.cloud.dialogflow_v2.types.Document.MetadataEntry]): + Optional. Metadata for the document. The metadata supports + arbitrary key-value pairs. Suggested use cases include + storing a document's title, an external URL distinct from + the document's content_uri, etc. The max size of a ``key`` + or a ``value`` of the metadata is 1024 bytes. + """ + class KnowledgeType(proto.Enum): + r"""The knowledge type of document content.""" + KNOWLEDGE_TYPE_UNSPECIFIED = 0 + FAQ = 1 + EXTRACTIVE_QA = 2 + ARTICLE_SUGGESTION = 3 + + class ReloadStatus(proto.Message): + r"""The status of a reload attempt. + + Attributes: + time (google.protobuf.timestamp_pb2.Timestamp): + The time of a reload attempt. + This reload may have been triggered + automatically or manually and may not have + succeeded. + status (google.rpc.status_pb2.Status): + The status of a reload attempt or the initial + load. + """ + + time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + mime_type = proto.Field( + proto.STRING, + number=3, + ) + knowledge_types = proto.RepeatedField( + proto.ENUM, + number=4, + enum=KnowledgeType, + ) + content_uri = proto.Field( + proto.STRING, + number=5, + oneof='source', + ) + raw_content = proto.Field( + proto.BYTES, + number=9, + oneof='source', + ) + enable_auto_reload = proto.Field( + proto.BOOL, + number=11, + ) + latest_reload_status = proto.Field( + proto.MESSAGE, + number=12, + message=ReloadStatus, + ) + metadata = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + + +class GetDocumentRequest(proto.Message): + r"""Request message for + [Documents.GetDocument][google.cloud.dialogflow.v2.Documents.GetDocument]. + + Attributes: + name (str): + Required. The name of the document to retrieve. Format + ``projects//locations//knowledgeBases//documents/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListDocumentsRequest(proto.Message): + r"""Request message for + [Documents.ListDocuments][google.cloud.dialogflow.v2.Documents.ListDocuments]. + + Attributes: + parent (str): + Required. The knowledge base to list all documents for. + Format: + ``projects//locations//knowledgeBases/``. + page_size (int): + The maximum number of items to return in a + single page. By default 10 and at most 100. + page_token (str): + The next_page_token value returned from a previous list + request. + filter (str): + The filter expression used to filter documents returned by + the list method. The expression has the following syntax: + + [AND ] ... + + The following fields and operators are supported: + + - knowledge_types with has(:) operator + - display_name with has(:) operator + - state with equals(=) operator + + Examples: + + - "knowledge_types:FAQ" matches documents with FAQ + knowledge type. + - "display_name:customer" matches documents whose display + name contains "customer". + - "state=ACTIVE" matches documents with ACTIVE state. + - "knowledge_types:FAQ AND state=ACTIVE" matches all active + FAQ documents. + + For more information about filtering, see `API + Filtering `__. + """ + + 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 ListDocumentsResponse(proto.Message): + r"""Response message for + [Documents.ListDocuments][google.cloud.dialogflow.v2.Documents.ListDocuments]. + + Attributes: + documents (Sequence[google.cloud.dialogflow_v2.types.Document]): + The list of documents. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + documents = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Document', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateDocumentRequest(proto.Message): + r"""Request message for + [Documents.CreateDocument][google.cloud.dialogflow.v2.Documents.CreateDocument]. + + Attributes: + parent (str): + Required. The knowledge base to create a document for. + Format: + ``projects//locations//knowledgeBases/``. + document (google.cloud.dialogflow_v2.types.Document): + Required. The document to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + document = proto.Field( + proto.MESSAGE, + number=2, + message='Document', + ) + + +class DeleteDocumentRequest(proto.Message): + r"""Request message for + [Documents.DeleteDocument][google.cloud.dialogflow.v2.Documents.DeleteDocument]. + + Attributes: + name (str): + Required. The name of the document to delete. Format: + ``projects//locations//knowledgeBases//documents/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateDocumentRequest(proto.Message): + r"""Request message for + [Documents.UpdateDocument][google.cloud.dialogflow.v2.Documents.UpdateDocument]. + + Attributes: + document (google.cloud.dialogflow_v2.types.Document): + Required. The document to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Not specified means ``update all``. Currently, + only ``display_name`` can be updated, an InvalidArgument + will be returned for attempting to update other fields. + """ + + document = proto.Field( + proto.MESSAGE, + number=1, + message='Document', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ReloadDocumentRequest(proto.Message): + r"""Request message for + [Documents.ReloadDocument][google.cloud.dialogflow.v2.Documents.ReloadDocument]. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Required. The name of the document to reload. Format: + ``projects//locations//knowledgeBases//documents/`` + content_uri (str): + Optional. The path of gcs source file for reloading document + content. For now, only gcs uri is supported. + + For documents stored in Google Cloud Storage, these URIs + must have the form ``gs:///``. + + This field is a member of `oneof`_ ``source``. + import_gcs_custom_metadata (bool): + Optional. Whether to import custom metadata + from Google Cloud Storage. Only valid when the + document source is Google Cloud Storage URI. + smart_messaging_partial_update (bool): + Optional. When enabled, the reload request is + to apply partial update to the smart messaging + allowlist. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + content_uri = proto.Field( + proto.STRING, + number=3, + oneof='source', + ) + import_gcs_custom_metadata = proto.Field( + proto.BOOL, + number=4, + ) + smart_messaging_partial_update = proto.Field( + proto.BOOL, + number=5, + ) + + +class ExportDocumentRequest(proto.Message): + r"""Request message for + [Documents.ExportDocument][google.cloud.dialogflow.v2.Documents.ExportDocument]. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Required. The name of the document to export. Format: + ``projects//locations//knowledgeBases//documents/``. + gcs_destination (google.cloud.dialogflow_v2.types.GcsDestination): + Cloud Storage file path to export the + document. + + This field is a member of `oneof`_ ``destination``. + export_full_content (bool): + When enabled, export the full content of the + document including empirical probability. + smart_messaging_partial_update (bool): + When enabled, export the smart messaging + allowlist document for partial update. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + gcs_destination = proto.Field( + proto.MESSAGE, + number=2, + oneof='destination', + message=gcs.GcsDestination, + ) + export_full_content = proto.Field( + proto.BOOL, + number=3, + ) + smart_messaging_partial_update = proto.Field( + proto.BOOL, + number=5, + ) + + +class KnowledgeOperationMetadata(proto.Message): + r"""Metadata in google::longrunning::Operation for Knowledge + operations. + + Attributes: + state (google.cloud.dialogflow_v2.types.KnowledgeOperationMetadata.State): + Output only. The current state of this + operation. + """ + class State(proto.Enum): + r"""States of the operation.""" + STATE_UNSPECIFIED = 0 + PENDING = 1 + RUNNING = 2 + DONE = 3 + + state = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/entity_type.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/entity_type.py new file mode 100644 index 000000000..9d1105bb5 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/entity_type.py @@ -0,0 +1,573 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + 'EntityType', + 'ListEntityTypesRequest', + 'ListEntityTypesResponse', + 'GetEntityTypeRequest', + 'CreateEntityTypeRequest', + 'UpdateEntityTypeRequest', + 'DeleteEntityTypeRequest', + 'BatchUpdateEntityTypesRequest', + 'BatchUpdateEntityTypesResponse', + 'BatchDeleteEntityTypesRequest', + 'BatchCreateEntitiesRequest', + 'BatchUpdateEntitiesRequest', + 'BatchDeleteEntitiesRequest', + 'EntityTypeBatch', + }, +) + + +class EntityType(proto.Message): + r"""Each intent parameter has a type, called the entity type, which + dictates exactly how data from an end-user expression is extracted. + + Dialogflow provides predefined system entities that can match many + common types of data. For example, there are system entities for + matching dates, times, colors, email addresses, and so on. You can + also create your own custom entities for matching custom data. For + example, you could define a vegetable entity that can match the + types of vegetables available for purchase with a grocery store + agent. + + For more information, see the `Entity + guide `__. + + Attributes: + name (str): + The unique identifier of the entity type. Required for + [EntityTypes.UpdateEntityType][google.cloud.dialogflow.v2.EntityTypes.UpdateEntityType] + and + [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntityTypes] + methods. Format: + ``projects//agent/entityTypes/``. + display_name (str): + Required. The name of the entity type. + kind (google.cloud.dialogflow_v2.types.EntityType.Kind): + Required. Indicates the kind of entity type. + auto_expansion_mode (google.cloud.dialogflow_v2.types.EntityType.AutoExpansionMode): + Optional. Indicates whether the entity type + can be automatically expanded. + entities (Sequence[google.cloud.dialogflow_v2.types.EntityType.Entity]): + Optional. The collection of entity entries + associated with the entity type. + enable_fuzzy_extraction (bool): + Optional. Enables fuzzy entity extraction + during classification. + """ + class Kind(proto.Enum): + r"""Represents kinds of entities.""" + KIND_UNSPECIFIED = 0 + KIND_MAP = 1 + KIND_LIST = 2 + KIND_REGEXP = 3 + + class AutoExpansionMode(proto.Enum): + r"""Represents different entity type expansion modes. Automated + expansion allows an agent to recognize values that have not been + explicitly listed in the entity (for example, new kinds of + shopping list items). + """ + AUTO_EXPANSION_MODE_UNSPECIFIED = 0 + AUTO_EXPANSION_MODE_DEFAULT = 1 + + class Entity(proto.Message): + r"""An **entity entry** for an associated entity type. + + Attributes: + value (str): + Required. The primary value associated with this entity + entry. For example, if the entity type is *vegetable*, the + value could be *scallions*. + + For ``KIND_MAP`` entity types: + + - A reference value to be used in place of synonyms. + + For ``KIND_LIST`` entity types: + + - A string that can contain references to other entity + types (with or without aliases). + synonyms (Sequence[str]): + Required. A collection of value synonyms. For example, if + the entity type is *vegetable*, and ``value`` is + *scallions*, a synonym could be *green onions*. + + For ``KIND_LIST`` entity types: + + - This collection must contain exactly one synonym equal to + ``value``. + """ + + value = proto.Field( + proto.STRING, + number=1, + ) + synonyms = proto.RepeatedField( + proto.STRING, + number=2, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + kind = proto.Field( + proto.ENUM, + number=3, + enum=Kind, + ) + auto_expansion_mode = proto.Field( + proto.ENUM, + number=4, + enum=AutoExpansionMode, + ) + entities = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=Entity, + ) + enable_fuzzy_extraction = proto.Field( + proto.BOOL, + number=7, + ) + + +class ListEntityTypesRequest(proto.Message): + r"""The request message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2.EntityTypes.ListEntityTypes]. + + Attributes: + parent (str): + Required. The agent to list all entity types from. Format: + ``projects//agent``. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class ListEntityTypesResponse(proto.Message): + r"""The response message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2.EntityTypes.ListEntityTypes]. + + Attributes: + entity_types (Sequence[google.cloud.dialogflow_v2.types.EntityType]): + The list of agent entity types. There will be a maximum + number of items returned based on the page_size field in the + request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + entity_types = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='EntityType', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetEntityTypeRequest(proto.Message): + r"""The request message for + [EntityTypes.GetEntityType][google.cloud.dialogflow.v2.EntityTypes.GetEntityType]. + + Attributes: + name (str): + Required. The name of the entity type. Format: + ``projects//agent/entityTypes/``. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateEntityTypeRequest(proto.Message): + r"""The request message for + [EntityTypes.CreateEntityType][google.cloud.dialogflow.v2.EntityTypes.CreateEntityType]. + + Attributes: + parent (str): + Required. The agent to create a entity type for. Format: + ``projects//agent``. + entity_type (google.cloud.dialogflow_v2.types.EntityType): + Required. The entity type to create. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + entity_type = proto.Field( + proto.MESSAGE, + number=2, + message='EntityType', + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateEntityTypeRequest(proto.Message): + r"""The request message for + [EntityTypes.UpdateEntityType][google.cloud.dialogflow.v2.EntityTypes.UpdateEntityType]. + + Attributes: + entity_type (google.cloud.dialogflow_v2.types.EntityType): + Required. The entity type to update. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which fields + get updated. + """ + + entity_type = proto.Field( + proto.MESSAGE, + number=1, + message='EntityType', + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteEntityTypeRequest(proto.Message): + r"""The request message for + [EntityTypes.DeleteEntityType][google.cloud.dialogflow.v2.EntityTypes.DeleteEntityType]. + + Attributes: + name (str): + Required. The name of the entity type to delete. Format: + ``projects//agent/entityTypes/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class BatchUpdateEntityTypesRequest(proto.Message): + r"""The request message for + [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntityTypes]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The name of the agent to update or create entity + types in. Format: ``projects//agent``. + entity_type_batch_uri (str): + The URI to a Google Cloud Storage file + containing entity types to update or create. The + file format can either be a serialized proto (of + EntityBatch type) or a JSON object. Note: The + URI must start with "gs://". + + This field is a member of `oneof`_ ``entity_type_batch``. + entity_type_batch_inline (google.cloud.dialogflow_v2.types.EntityTypeBatch): + The collection of entity types to update or + create. + + This field is a member of `oneof`_ ``entity_type_batch``. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which fields + get updated. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + entity_type_batch_uri = proto.Field( + proto.STRING, + number=2, + oneof='entity_type_batch', + ) + entity_type_batch_inline = proto.Field( + proto.MESSAGE, + number=3, + oneof='entity_type_batch', + message='EntityTypeBatch', + ) + language_code = proto.Field( + proto.STRING, + number=4, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + + +class BatchUpdateEntityTypesResponse(proto.Message): + r"""The response message for + [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntityTypes]. + + Attributes: + entity_types (Sequence[google.cloud.dialogflow_v2.types.EntityType]): + The collection of updated or created entity + types. + """ + + entity_types = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='EntityType', + ) + + +class BatchDeleteEntityTypesRequest(proto.Message): + r"""The request message for + [EntityTypes.BatchDeleteEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchDeleteEntityTypes]. + + Attributes: + parent (str): + Required. The name of the agent to delete all entities types + for. Format: ``projects//agent``. + entity_type_names (Sequence[str]): + Required. The names entity types to delete. All names must + point to the same agent as ``parent``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + entity_type_names = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class BatchCreateEntitiesRequest(proto.Message): + r"""The request message for + [EntityTypes.BatchCreateEntities][google.cloud.dialogflow.v2.EntityTypes.BatchCreateEntities]. + + Attributes: + parent (str): + Required. The name of the entity type to create entities in. + Format: + ``projects//agent/entityTypes/``. + entities (Sequence[google.cloud.dialogflow_v2.types.EntityType.Entity]): + Required. The entities to create. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + entities = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='EntityType.Entity', + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class BatchUpdateEntitiesRequest(proto.Message): + r"""The request message for + [EntityTypes.BatchUpdateEntities][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntities]. + + Attributes: + parent (str): + Required. The name of the entity type to update or create + entities in. Format: + ``projects//agent/entityTypes/``. + entities (Sequence[google.cloud.dialogflow_v2.types.EntityType.Entity]): + Required. The entities to update or create. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which fields + get updated. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + entities = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='EntityType.Entity', + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + + +class BatchDeleteEntitiesRequest(proto.Message): + r"""The request message for + [EntityTypes.BatchDeleteEntities][google.cloud.dialogflow.v2.EntityTypes.BatchDeleteEntities]. + + Attributes: + parent (str): + Required. The name of the entity type to delete entries for. + Format: + ``projects//agent/entityTypes/``. + entity_values (Sequence[str]): + Required. The reference ``values`` of the entities to + delete. Note that these are not fully-qualified names, i.e. + they don't start with ``projects/``. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + entity_values = proto.RepeatedField( + proto.STRING, + number=2, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class EntityTypeBatch(proto.Message): + r"""This message is a wrapper around a collection of entity + types. + + Attributes: + entity_types (Sequence[google.cloud.dialogflow_v2.types.EntityType]): + A collection of entity types. + """ + + entity_types = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='EntityType', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/environment.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/environment.py new file mode 100644 index 000000000..04b75a40d --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/environment.py @@ -0,0 +1,470 @@ +# -*- 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.dialogflow_v2.types import audio_config +from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + 'Environment', + 'TextToSpeechSettings', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'GetEnvironmentRequest', + 'CreateEnvironmentRequest', + 'UpdateEnvironmentRequest', + 'DeleteEnvironmentRequest', + 'GetEnvironmentHistoryRequest', + 'EnvironmentHistory', + }, +) + + +class Environment(proto.Message): + r"""You can create multiple versions of your agent and publish them to + separate environments. + + When you edit an agent, you are editing the draft agent. At any + point, you can save the draft agent as an agent version, which is an + immutable snapshot of your agent. + + When you save the draft agent, it is published to the default + environment. When you create agent versions, you can publish them to + custom environments. You can create a variety of custom environments + for: + + - testing + - development + - production + - etc. + + For more information, see the `versions and environments + guide `__. + + Attributes: + name (str): + Output only. The unique identifier of this agent + environment. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + + The environment ID for the default environment is ``-``. + description (str): + Optional. The developer-provided description + for this environment. The maximum length is 500 + characters. If exceeded, the request is + rejected. + agent_version (str): + Optional. The agent version loaded into this environment. + Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + state (google.cloud.dialogflow_v2.types.Environment.State): + Output only. The state of this environment. + This field is read-only, i.e., it cannot be set + by create and update methods. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last update time of this + environment. This field is read-only, i.e., it + cannot be set by create and update methods. + text_to_speech_settings (google.cloud.dialogflow_v2.types.TextToSpeechSettings): + Optional. Text to speech settings for this + environment. + fulfillment (google.cloud.dialogflow_v2.types.Fulfillment): + Optional. The fulfillment settings to use for + this environment. + """ + class State(proto.Enum): + r"""Represents an environment state. When an environment is pointed to a + new agent version, the environment is temporarily set to the + ``LOADING`` state. During that time, the environment keeps on + serving the previous version of the agent. After the new agent + version is done loading, the environment is set back to the + ``RUNNING`` state. + """ + STATE_UNSPECIFIED = 0 + STOPPED = 1 + LOADING = 2 + RUNNING = 3 + + name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + agent_version = proto.Field( + proto.STRING, + number=3, + ) + state = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + update_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + text_to_speech_settings = proto.Field( + proto.MESSAGE, + number=7, + message='TextToSpeechSettings', + ) + fulfillment = proto.Field( + proto.MESSAGE, + number=8, + message=gcd_fulfillment.Fulfillment, + ) + + +class TextToSpeechSettings(proto.Message): + r"""Instructs the speech synthesizer on how to generate the + output audio content. + + Attributes: + enable_text_to_speech (bool): + Optional. Indicates whether text to speech is + enabled. Even when this field is false, other + settings in this proto are still retained. + output_audio_encoding (google.cloud.dialogflow_v2.types.OutputAudioEncoding): + Required. Audio encoding of the synthesized + audio content. + sample_rate_hertz (int): + Optional. The synthesis sample rate (in + hertz) for this audio. If not provided, then the + synthesizer will use the default sample rate + based on the audio encoding. If this is + different from the voice's natural sample rate, + then the synthesizer will honor this request by + converting to the desired sample rate (which + might result in worse audio quality). + synthesize_speech_configs (Sequence[google.cloud.dialogflow_v2.types.TextToSpeechSettings.SynthesizeSpeechConfigsEntry]): + Optional. Configuration of how speech should + be synthesized, mapping from language + (https://cloud.google.com/dialogflow/docs/reference/language) + to SynthesizeSpeechConfig. + """ + + enable_text_to_speech = proto.Field( + proto.BOOL, + number=1, + ) + output_audio_encoding = proto.Field( + proto.ENUM, + number=2, + enum=audio_config.OutputAudioEncoding, + ) + sample_rate_hertz = proto.Field( + proto.INT32, + number=3, + ) + synthesize_speech_configs = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message=audio_config.SynthesizeSpeechConfig, + ) + + +class ListEnvironmentsRequest(proto.Message): + r"""The request message for + [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. + + Attributes: + parent (str): + Required. The agent to list all environments from. Format: + + - ``projects//agent`` + - ``projects//locations//agent`` + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListEnvironmentsResponse(proto.Message): + r"""The response message for + [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. + + Attributes: + environments (Sequence[google.cloud.dialogflow_v2.types.Environment]): + The list of agent environments. There will be a maximum + number of items returned based on the page_size field in the + request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + environments = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Environment', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.v2.Environments.GetEnvironment]. + + Attributes: + name (str): + Required. The name of the environment. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + + The environment ID for the default environment is ``-``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.v2.Environments.CreateEnvironment]. + + Attributes: + parent (str): + Required. The agent to create an environment for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + environment (google.cloud.dialogflow_v2.types.Environment): + Required. The environment to create. + environment_id (str): + Required. The unique id of the new + environment. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + environment = proto.Field( + proto.MESSAGE, + number=2, + message='Environment', + ) + environment_id = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.v2.Environments.UpdateEnvironment]. + + Attributes: + environment (google.cloud.dialogflow_v2.types.Environment): + Required. The environment to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. + allow_load_to_draft_and_discard_changes (bool): + Optional. This field is used to prevent accidental overwrite + of the default environment, which is an operation that + cannot be undone. To confirm that the caller desires this + overwrite, this field must be explicitly set to true when + updating the default environment (environment ID = ``-``). + """ + + environment = proto.Field( + proto.MESSAGE, + number=1, + message='Environment', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_load_to_draft_and_discard_changes = proto.Field( + proto.BOOL, + number=3, + ) + + +class DeleteEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.v2.Environments.DeleteEnvironment]. + + Attributes: + name (str): + Required. The name of the environment to delete. / Format: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + + The environment ID for the default environment is ``-``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetEnvironmentHistoryRequest(proto.Message): + r"""The request message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. + + Attributes: + parent (str): + Required. The name of the environment to retrieve history + for. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + + The environment ID for the default environment is ``-``. + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class EnvironmentHistory(proto.Message): + r"""The response message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. + + Attributes: + parent (str): + Output only. The name of the environment this history is + for. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + + The environment ID for the default environment is ``-``. + entries (Sequence[google.cloud.dialogflow_v2.types.EnvironmentHistory.Entry]): + Output only. The list of agent environments. There will be a + maximum number of items returned based on the page_size + field in the request. + next_page_token (str): + Output only. Token to retrieve the next page + of results, or empty if there are no more + results in the list. + """ + + class Entry(proto.Message): + r"""Represents an environment history entry. + + Attributes: + agent_version (str): + The agent version loaded into this + environment history entry. + description (str): + The developer-provided description for this + environment history entry. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The creation time of this environment history + entry. + """ + + agent_version = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + create_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + @property + def raw_page(self): + return self + + parent = proto.Field( + proto.STRING, + number=1, + ) + entries = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Entry, + ) + next_page_token = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/fulfillment.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/fulfillment.py new file mode 100644 index 000000000..8d7de161f --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/fulfillment.py @@ -0,0 +1,207 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + 'Fulfillment', + 'GetFulfillmentRequest', + 'UpdateFulfillmentRequest', + }, +) + + +class Fulfillment(proto.Message): + r"""By default, your agent responds to a matched intent with a static + response. As an alternative, you can provide a more dynamic response + by using fulfillment. When you enable fulfillment for an intent, + Dialogflow responds to that intent by calling a service that you + define. For example, if an end-user wants to schedule a haircut on + Friday, your service can check your database and respond to the + end-user with availability information for Friday. + + For more information, see the `fulfillment + guide `__. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Required. The unique identifier of the fulfillment. + Supported formats: + + - ``projects//agent/fulfillment`` + - ``projects//locations//agent/fulfillment`` + + This field is not used for Fulfillment in an Environment. + display_name (str): + Optional. The human-readable name of the + fulfillment, unique within the agent. + This field is not used for Fulfillment in an + Environment. + generic_web_service (google.cloud.dialogflow_v2.types.Fulfillment.GenericWebService): + Configuration for a generic web service. + + This field is a member of `oneof`_ ``fulfillment``. + enabled (bool): + Optional. Whether fulfillment is enabled. + features (Sequence[google.cloud.dialogflow_v2.types.Fulfillment.Feature]): + Optional. The field defines whether the + fulfillment is enabled for certain features. + """ + + class GenericWebService(proto.Message): + r"""Represents configuration for a generic web service. + Dialogflow supports two mechanisms for authentications: - Basic + authentication with username and password. + - Authentication with additional authentication headers. More + information could be found at: + https://cloud.google.com/dialogflow/docs/fulfillment-configure. + + Attributes: + uri (str): + Required. The fulfillment URI for receiving + POST requests. It must use https protocol. + username (str): + Optional. The user name for HTTP Basic + authentication. + password (str): + Optional. The password for HTTP Basic + authentication. + request_headers (Sequence[google.cloud.dialogflow_v2.types.Fulfillment.GenericWebService.RequestHeadersEntry]): + Optional. The HTTP request headers to send + together with fulfillment requests. + is_cloud_function (bool): + Optional. Indicates if generic web service is created + through Cloud Functions integration. Defaults to false. + + is_cloud_function is deprecated. Cloud functions can be + configured by its uri as a regular web service now. + """ + + uri = proto.Field( + proto.STRING, + number=1, + ) + username = proto.Field( + proto.STRING, + number=2, + ) + password = proto.Field( + proto.STRING, + number=3, + ) + request_headers = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + is_cloud_function = proto.Field( + proto.BOOL, + number=5, + ) + + class Feature(proto.Message): + r"""Whether fulfillment is enabled for the specific feature. + + Attributes: + type_ (google.cloud.dialogflow_v2.types.Fulfillment.Feature.Type): + The type of the feature that enabled for + fulfillment. + """ + class Type(proto.Enum): + r"""The type of the feature.""" + TYPE_UNSPECIFIED = 0 + SMALLTALK = 1 + + type_ = proto.Field( + proto.ENUM, + number=1, + enum='Fulfillment.Feature.Type', + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + generic_web_service = proto.Field( + proto.MESSAGE, + number=3, + oneof='fulfillment', + message=GenericWebService, + ) + enabled = proto.Field( + proto.BOOL, + number=4, + ) + features = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=Feature, + ) + + +class GetFulfillmentRequest(proto.Message): + r"""The request message for + [Fulfillments.GetFulfillment][google.cloud.dialogflow.v2.Fulfillments.GetFulfillment]. + + Attributes: + name (str): + Required. The name of the fulfillment. Format: + ``projects//agent/fulfillment``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateFulfillmentRequest(proto.Message): + r"""The request message for + [Fulfillments.UpdateFulfillment][google.cloud.dialogflow.v2.Fulfillments.UpdateFulfillment]. + + Attributes: + fulfillment (google.cloud.dialogflow_v2.types.Fulfillment): + Required. The fulfillment to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. If the mask is not present, all + fields will be updated. + """ + + fulfillment = proto.Field( + proto.MESSAGE, + number=1, + message='Fulfillment', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/gcs.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/gcs.py new file mode 100644 index 000000000..7d3763ed5 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/gcs.py @@ -0,0 +1,46 @@ +# -*- 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.dialogflow.v2', + manifest={ + 'GcsDestination', + }, +) + + +class GcsDestination(proto.Message): + r"""Google Cloud Storage location for the output. + + Attributes: + uri (str): + The Google Cloud Storage URIs for the output. + A URI is of the form: + gs://bucket/object-prefix-or-name + Whether a prefix or name is used depends on the + use case. The requesting user must have "write- + permission" to the bucket. + """ + + uri = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/human_agent_assistant_event.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/human_agent_assistant_event.py new file mode 100644 index 000000000..625acf227 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/human_agent_assistant_event.py @@ -0,0 +1,61 @@ +# -*- 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.dialogflow_v2.types import participant as gcd_participant + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + 'HumanAgentAssistantEvent', + }, +) + + +class HumanAgentAssistantEvent(proto.Message): + r"""Represents a notification sent to Cloud Pub/Sub subscribers + for human agent assistant events in a specific conversation. + + Attributes: + conversation (str): + The conversation this notification refers to. Format: + ``projects//conversations/``. + participant (str): + The participant that the suggestion is compiled for. Format: + ``projects//conversations//participants/``. + It will not be set in legacy workflow. + suggestion_results (Sequence[google.cloud.dialogflow_v2.types.SuggestionResult]): + The suggestion results payload that this + notification refers to. + """ + + conversation = proto.Field( + proto.STRING, + number=1, + ) + participant = proto.Field( + proto.STRING, + number=3, + ) + suggestion_results = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=gcd_participant.SuggestionResult, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/intent.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/intent.py new file mode 100644 index 000000000..705434705 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/intent.py @@ -0,0 +1,1702 @@ +# -*- 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.dialogflow_v2.types import context +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + 'IntentView', + 'Intent', + 'ListIntentsRequest', + 'ListIntentsResponse', + 'GetIntentRequest', + 'CreateIntentRequest', + 'UpdateIntentRequest', + 'DeleteIntentRequest', + 'BatchUpdateIntentsRequest', + 'BatchUpdateIntentsResponse', + 'BatchDeleteIntentsRequest', + 'IntentBatch', + }, +) + + +class IntentView(proto.Enum): + r"""Represents the options for views of an intent. + An intent can be a sizable object. Therefore, we provide a + resource view that does not return training phrases in the + response by default. + """ + INTENT_VIEW_UNSPECIFIED = 0 + INTENT_VIEW_FULL = 1 + + +class Intent(proto.Message): + r"""An intent categorizes an end-user's intention for one conversation + turn. For each agent, you define many intents, where your combined + intents can handle a complete conversation. When an end-user writes + or says something, referred to as an end-user expression or end-user + input, Dialogflow matches the end-user input to the best intent in + your agent. Matching an intent is also known as intent + classification. + + For more information, see the `intent + guide `__. + + Attributes: + name (str): + Optional. The unique identifier of this intent. Required for + [Intents.UpdateIntent][google.cloud.dialogflow.v2.Intents.UpdateIntent] + and + [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2.Intents.BatchUpdateIntents] + methods. Format: + ``projects//agent/intents/``. + display_name (str): + Required. The name of this intent. + webhook_state (google.cloud.dialogflow_v2.types.Intent.WebhookState): + Optional. Indicates whether webhooks are + enabled for the intent. + priority (int): + Optional. The priority of this intent. Higher numbers + represent higher priorities. + + - If the supplied value is unspecified or 0, the service + translates the value to 500,000, which corresponds to the + ``Normal`` priority in the console. + - If the supplied value is negative, the intent is ignored + in runtime detect intent requests. + is_fallback (bool): + Optional. Indicates whether this is a + fallback intent. + ml_disabled (bool): + Optional. Indicates whether Machine Learning is disabled for + the intent. Note: If ``ml_disabled`` setting is set to true, + then this intent is not taken into account during inference + in ``ML ONLY`` match mode. Also, auto-markup in the UI is + turned off. + live_agent_handoff (bool): + Optional. Indicates that a live agent should be brought in + to handle the interaction with the user. In most cases, when + you set this flag to true, you would also want to set + end_interaction to true as well. Default is false. + end_interaction (bool): + Optional. Indicates that this intent ends an + interaction. Some integrations (e.g., Actions on + Google or Dialogflow phone gateway) use this + information to close interaction with an end + user. Default is false. + input_context_names (Sequence[str]): + Optional. The list of context names required for this intent + to be triggered. Format: + ``projects//agent/sessions/-/contexts/``. + events (Sequence[str]): + Optional. The collection of event names that + trigger the intent. If the collection of input + contexts is not empty, all of the contexts must + be present in the active user session for an + event to trigger this intent. Event names are + limited to 150 characters. + training_phrases (Sequence[google.cloud.dialogflow_v2.types.Intent.TrainingPhrase]): + Optional. The collection of examples that the + agent is trained on. + action (str): + Optional. The name of the action associated + with the intent. Note: The action name must not + contain whitespaces. + output_contexts (Sequence[google.cloud.dialogflow_v2.types.Context]): + Optional. The collection of contexts that are activated when + the intent is matched. Context messages in this collection + should not set the parameters field. Setting the + ``lifespan_count`` to 0 will reset the context when the + intent is matched. Format: + ``projects//agent/sessions/-/contexts/``. + reset_contexts (bool): + Optional. Indicates whether to delete all + contexts in the current session when this intent + is matched. + parameters (Sequence[google.cloud.dialogflow_v2.types.Intent.Parameter]): + Optional. The collection of parameters + associated with the intent. + messages (Sequence[google.cloud.dialogflow_v2.types.Intent.Message]): + Optional. The collection of rich messages corresponding to + the ``Response`` field in the Dialogflow console. + default_response_platforms (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.Platform]): + Optional. The list of platforms for which the first + responses will be copied from the messages in + PLATFORM_UNSPECIFIED (i.e. default platform). + root_followup_intent_name (str): + Output only. Read-only. The unique identifier of the root + intent in the chain of followup intents. It identifies the + correct followup intents chain for this intent. We populate + this field only in the output. + + Format: ``projects//agent/intents/``. + parent_followup_intent_name (str): + Read-only after creation. The unique identifier of the + parent intent in the chain of followup intents. You can set + this field when creating an intent, for example with + [CreateIntent][google.cloud.dialogflow.v2.Intents.CreateIntent] + or + [BatchUpdateIntents][google.cloud.dialogflow.v2.Intents.BatchUpdateIntents], + in order to make this intent a followup intent. + + It identifies the parent followup intent. Format: + ``projects//agent/intents/``. + followup_intent_info (Sequence[google.cloud.dialogflow_v2.types.Intent.FollowupIntentInfo]): + Output only. Read-only. Information about all + followup intents that have this intent as a + direct or indirect parent. We populate this + field only in the output. + """ + class WebhookState(proto.Enum): + r"""Represents the different states that webhooks can be in.""" + WEBHOOK_STATE_UNSPECIFIED = 0 + WEBHOOK_STATE_ENABLED = 1 + WEBHOOK_STATE_ENABLED_FOR_SLOT_FILLING = 2 + + class TrainingPhrase(proto.Message): + r"""Represents an example that the agent is trained on. + + Attributes: + name (str): + Output only. The unique identifier of this + training phrase. + type_ (google.cloud.dialogflow_v2.types.Intent.TrainingPhrase.Type): + Required. The type of the training phrase. + parts (Sequence[google.cloud.dialogflow_v2.types.Intent.TrainingPhrase.Part]): + Required. The ordered list of training phrase parts. The + parts are concatenated in order to form the training phrase. + + Note: The API does not automatically annotate training + phrases like the Dialogflow Console does. + + Note: Do not forget to include whitespace at part + boundaries, so the training phrase is well formatted when + the parts are concatenated. + + If the training phrase does not need to be annotated with + parameters, you just need a single part with only the + [Part.text][google.cloud.dialogflow.v2.Intent.TrainingPhrase.Part.text] + field set. + + If you want to annotate the training phrase, you must create + multiple parts, where the fields of each part are populated + in one of two ways: + + - ``Part.text`` is set to a part of the phrase that has no + parameters. + - ``Part.text`` is set to a part of the phrase that you + want to annotate, and the ``entity_type``, ``alias``, and + ``user_defined`` fields are all set. + times_added_count (int): + Optional. Indicates how many times this + example was added to the intent. Each time a + developer adds an existing sample by editing an + intent or training, this counter is increased. + """ + class Type(proto.Enum): + r"""Represents different types of training phrases.""" + TYPE_UNSPECIFIED = 0 + EXAMPLE = 1 + TEMPLATE = 2 + + class Part(proto.Message): + r"""Represents a part of a training phrase. + + Attributes: + text (str): + Required. The text for this part. + entity_type (str): + Optional. The entity type name prefixed with ``@``. This + field is required for annotated parts of the training + phrase. + alias (str): + Optional. The parameter name for the value + extracted from the annotated part of the + example. This field is required for annotated + parts of the training phrase. + user_defined (bool): + Optional. Indicates whether the text was + manually annotated. This field is set to true + when the Dialogflow Console is used to manually + annotate the part. When creating an annotated + part with the API, you must set this to true. + """ + + text = proto.Field( + proto.STRING, + number=1, + ) + entity_type = proto.Field( + proto.STRING, + number=2, + ) + alias = proto.Field( + proto.STRING, + number=3, + ) + user_defined = proto.Field( + proto.BOOL, + number=4, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.ENUM, + number=2, + enum='Intent.TrainingPhrase.Type', + ) + parts = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Intent.TrainingPhrase.Part', + ) + times_added_count = proto.Field( + proto.INT32, + number=4, + ) + + class Parameter(proto.Message): + r"""Represents intent parameters. + + Attributes: + name (str): + The unique identifier of this parameter. + display_name (str): + Required. The name of the parameter. + value (str): + Optional. The definition of the parameter value. It can be: + + - a constant string, + - a parameter value defined as ``$parameter_name``, + - an original parameter value defined as + ``$parameter_name.original``, + - a parameter value from some context defined as + ``#context_name.parameter_name``. + default_value (str): + Optional. The default value to use when the ``value`` yields + an empty result. Default values can be extracted from + contexts by using the following syntax: + ``#context_name.parameter_name``. + entity_type_display_name (str): + Optional. The name of the entity type, prefixed with ``@``, + that describes values of the parameter. If the parameter is + required, this must be provided. + mandatory (bool): + Optional. Indicates whether the parameter is + required. That is, whether the intent cannot be + completed without collecting the parameter + value. + prompts (Sequence[str]): + Optional. The collection of prompts that the + agent can present to the user in order to + collect a value for the parameter. + is_list (bool): + Optional. Indicates whether the parameter + represents a list of values. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + value = proto.Field( + proto.STRING, + number=3, + ) + default_value = proto.Field( + proto.STRING, + number=4, + ) + entity_type_display_name = proto.Field( + proto.STRING, + number=5, + ) + mandatory = proto.Field( + proto.BOOL, + number=6, + ) + prompts = proto.RepeatedField( + proto.STRING, + number=7, + ) + is_list = proto.Field( + proto.BOOL, + number=8, + ) + + class Message(proto.Message): + r"""A rich response message. Corresponds to the intent ``Response`` + field in the Dialogflow console. For more information, see `Rich + response + messages `__. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + text (google.cloud.dialogflow_v2.types.Intent.Message.Text): + The text response. + + This field is a member of `oneof`_ ``message``. + image (google.cloud.dialogflow_v2.types.Intent.Message.Image): + The image response. + + This field is a member of `oneof`_ ``message``. + quick_replies (google.cloud.dialogflow_v2.types.Intent.Message.QuickReplies): + The quick replies response. + + This field is a member of `oneof`_ ``message``. + card (google.cloud.dialogflow_v2.types.Intent.Message.Card): + The card response. + + This field is a member of `oneof`_ ``message``. + payload (google.protobuf.struct_pb2.Struct): + A custom platform-specific response. + + This field is a member of `oneof`_ ``message``. + simple_responses (google.cloud.dialogflow_v2.types.Intent.Message.SimpleResponses): + The voice and text-only responses for Actions + on Google. + + This field is a member of `oneof`_ ``message``. + basic_card (google.cloud.dialogflow_v2.types.Intent.Message.BasicCard): + The basic card response for Actions on + Google. + + This field is a member of `oneof`_ ``message``. + suggestions (google.cloud.dialogflow_v2.types.Intent.Message.Suggestions): + The suggestion chips for Actions on Google. + + This field is a member of `oneof`_ ``message``. + link_out_suggestion (google.cloud.dialogflow_v2.types.Intent.Message.LinkOutSuggestion): + The link out suggestion chip for Actions on + Google. + + This field is a member of `oneof`_ ``message``. + list_select (google.cloud.dialogflow_v2.types.Intent.Message.ListSelect): + The list card response for Actions on Google. + + This field is a member of `oneof`_ ``message``. + carousel_select (google.cloud.dialogflow_v2.types.Intent.Message.CarouselSelect): + The carousel card response for Actions on + Google. + + This field is a member of `oneof`_ ``message``. + browse_carousel_card (google.cloud.dialogflow_v2.types.Intent.Message.BrowseCarouselCard): + Browse carousel card for Actions on Google. + + This field is a member of `oneof`_ ``message``. + table_card (google.cloud.dialogflow_v2.types.Intent.Message.TableCard): + Table card for Actions on Google. + + This field is a member of `oneof`_ ``message``. + media_content (google.cloud.dialogflow_v2.types.Intent.Message.MediaContent): + The media content card for Actions on Google. + + This field is a member of `oneof`_ ``message``. + platform (google.cloud.dialogflow_v2.types.Intent.Message.Platform): + Optional. The platform that this message is + intended for. + """ + class Platform(proto.Enum): + r"""The rich response message integration platform. See + `Integrations `__. + """ + PLATFORM_UNSPECIFIED = 0 + FACEBOOK = 1 + SLACK = 2 + TELEGRAM = 3 + KIK = 4 + SKYPE = 5 + LINE = 6 + VIBER = 7 + ACTIONS_ON_GOOGLE = 8 + GOOGLE_HANGOUTS = 11 + + class Text(proto.Message): + r"""The text response message. + + Attributes: + text (Sequence[str]): + Optional. The collection of the agent's + responses. + """ + + text = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class Image(proto.Message): + r"""The image response message. + + Attributes: + image_uri (str): + Optional. The public URI to an image file. + accessibility_text (str): + Optional. A text description of the image to + be used for accessibility, e.g., screen readers. + """ + + image_uri = proto.Field( + proto.STRING, + number=1, + ) + accessibility_text = proto.Field( + proto.STRING, + number=2, + ) + + class QuickReplies(proto.Message): + r"""The quick replies response message. + + Attributes: + title (str): + Optional. The title of the collection of + quick replies. + quick_replies (Sequence[str]): + Optional. The collection of quick replies. + """ + + title = proto.Field( + proto.STRING, + number=1, + ) + quick_replies = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class Card(proto.Message): + r"""The card response message. + + Attributes: + title (str): + Optional. The title of the card. + subtitle (str): + Optional. The subtitle of the card. + image_uri (str): + Optional. The public URI to an image file for + the card. + buttons (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.Card.Button]): + Optional. The collection of card buttons. + """ + + class Button(proto.Message): + r"""Contains information about a button. + + Attributes: + text (str): + Optional. The text to show on the button. + postback (str): + Optional. The text to send back to the + Dialogflow API or a URI to open. + """ + + text = proto.Field( + proto.STRING, + number=1, + ) + postback = proto.Field( + proto.STRING, + number=2, + ) + + title = proto.Field( + proto.STRING, + number=1, + ) + subtitle = proto.Field( + proto.STRING, + number=2, + ) + image_uri = proto.Field( + proto.STRING, + number=3, + ) + buttons = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Intent.Message.Card.Button', + ) + + class SimpleResponse(proto.Message): + r"""The simple response message containing speech or text. + + Attributes: + text_to_speech (str): + One of text_to_speech or ssml must be provided. The plain + text of the speech output. Mutually exclusive with ssml. + ssml (str): + One of text_to_speech or ssml must be provided. Structured + spoken response to the user in the SSML format. Mutually + exclusive with text_to_speech. + display_text (str): + Optional. The text to display. + """ + + text_to_speech = proto.Field( + proto.STRING, + number=1, + ) + ssml = proto.Field( + proto.STRING, + number=2, + ) + display_text = proto.Field( + proto.STRING, + number=3, + ) + + class SimpleResponses(proto.Message): + r"""The collection of simple response candidates. This message in + ``QueryResult.fulfillment_messages`` and + ``WebhookResponse.fulfillment_messages`` should contain only one + ``SimpleResponse``. + + Attributes: + simple_responses (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.SimpleResponse]): + Required. The list of simple responses. + """ + + simple_responses = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Intent.Message.SimpleResponse', + ) + + class BasicCard(proto.Message): + r"""The basic card message. Useful for displaying information. + + Attributes: + title (str): + Optional. The title of the card. + subtitle (str): + Optional. The subtitle of the card. + formatted_text (str): + Required, unless image is present. The body + text of the card. + image (google.cloud.dialogflow_v2.types.Intent.Message.Image): + Optional. The image for the card. + buttons (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.BasicCard.Button]): + Optional. The collection of card buttons. + """ + + class Button(proto.Message): + r"""The button object that appears at the bottom of a card. + + Attributes: + title (str): + Required. The title of the button. + open_uri_action (google.cloud.dialogflow_v2.types.Intent.Message.BasicCard.Button.OpenUriAction): + Required. Action to take when a user taps on + the button. + """ + + class OpenUriAction(proto.Message): + r"""Opens the given URI. + + Attributes: + uri (str): + Required. The HTTP or HTTPS scheme URI. + """ + + uri = proto.Field( + proto.STRING, + number=1, + ) + + title = proto.Field( + proto.STRING, + number=1, + ) + open_uri_action = proto.Field( + proto.MESSAGE, + number=2, + message='Intent.Message.BasicCard.Button.OpenUriAction', + ) + + title = proto.Field( + proto.STRING, + number=1, + ) + subtitle = proto.Field( + proto.STRING, + number=2, + ) + formatted_text = proto.Field( + proto.STRING, + number=3, + ) + image = proto.Field( + proto.MESSAGE, + number=4, + message='Intent.Message.Image', + ) + buttons = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='Intent.Message.BasicCard.Button', + ) + + class Suggestion(proto.Message): + r"""The suggestion chip message that the user can tap to quickly + post a reply to the conversation. + + Attributes: + title (str): + Required. The text shown the in the + suggestion chip. + """ + + title = proto.Field( + proto.STRING, + number=1, + ) + + class Suggestions(proto.Message): + r"""The collection of suggestions. + + Attributes: + suggestions (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.Suggestion]): + Required. The list of suggested replies. + """ + + suggestions = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Intent.Message.Suggestion', + ) + + class LinkOutSuggestion(proto.Message): + r"""The suggestion chip message that allows the user to jump out + to the app or website associated with this agent. + + Attributes: + destination_name (str): + Required. The name of the app or site this + chip is linking to. + uri (str): + Required. The URI of the app or site to open + when the user taps the suggestion chip. + """ + + destination_name = proto.Field( + proto.STRING, + number=1, + ) + uri = proto.Field( + proto.STRING, + number=2, + ) + + class ListSelect(proto.Message): + r"""The card for presenting a list of options to select from. + + Attributes: + title (str): + Optional. The overall title of the list. + items (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.ListSelect.Item]): + Required. List items. + subtitle (str): + Optional. Subtitle of the list. + """ + + class Item(proto.Message): + r"""An item in the list. + + Attributes: + info (google.cloud.dialogflow_v2.types.Intent.Message.SelectItemInfo): + Required. Additional information about this + option. + title (str): + Required. The title of the list item. + description (str): + Optional. The main text describing the item. + image (google.cloud.dialogflow_v2.types.Intent.Message.Image): + Optional. The image to display. + """ + + info = proto.Field( + proto.MESSAGE, + number=1, + message='Intent.Message.SelectItemInfo', + ) + title = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + image = proto.Field( + proto.MESSAGE, + number=4, + message='Intent.Message.Image', + ) + + title = proto.Field( + proto.STRING, + number=1, + ) + items = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Intent.Message.ListSelect.Item', + ) + subtitle = proto.Field( + proto.STRING, + number=3, + ) + + class CarouselSelect(proto.Message): + r"""The card for presenting a carousel of options to select from. + + Attributes: + items (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.CarouselSelect.Item]): + Required. Carousel items. + """ + + class Item(proto.Message): + r"""An item in the carousel. + + Attributes: + info (google.cloud.dialogflow_v2.types.Intent.Message.SelectItemInfo): + Required. Additional info about the option + item. + title (str): + Required. Title of the carousel item. + description (str): + Optional. The body text of the card. + image (google.cloud.dialogflow_v2.types.Intent.Message.Image): + Optional. The image to display. + """ + + info = proto.Field( + proto.MESSAGE, + number=1, + message='Intent.Message.SelectItemInfo', + ) + title = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + image = proto.Field( + proto.MESSAGE, + number=4, + message='Intent.Message.Image', + ) + + items = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Intent.Message.CarouselSelect.Item', + ) + + class SelectItemInfo(proto.Message): + r"""Additional info about the select item for when it is + triggered in a dialog. + + Attributes: + key (str): + Required. A unique key that will be sent back + to the agent if this response is given. + synonyms (Sequence[str]): + Optional. A list of synonyms that can also be + used to trigger this item in dialog. + """ + + key = proto.Field( + proto.STRING, + number=1, + ) + synonyms = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class MediaContent(proto.Message): + r"""The media content card for Actions on Google. + + Attributes: + media_type (google.cloud.dialogflow_v2.types.Intent.Message.MediaContent.ResponseMediaType): + Optional. What type of media is the content + (ie "audio"). + media_objects (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.MediaContent.ResponseMediaObject]): + Required. List of media objects. + """ + class ResponseMediaType(proto.Enum): + r"""Format of response media type.""" + RESPONSE_MEDIA_TYPE_UNSPECIFIED = 0 + AUDIO = 1 + + class ResponseMediaObject(proto.Message): + r"""Response media object for media content card. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Required. Name of media card. + description (str): + Optional. Description of media card. + large_image (google.cloud.dialogflow_v2.types.Intent.Message.Image): + Optional. Image to display above media + content. + + This field is a member of `oneof`_ ``image``. + icon (google.cloud.dialogflow_v2.types.Intent.Message.Image): + Optional. Icon to display above media + content. + + This field is a member of `oneof`_ ``image``. + content_url (str): + Required. Url where the media is stored. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + large_image = proto.Field( + proto.MESSAGE, + number=3, + oneof='image', + message='Intent.Message.Image', + ) + icon = proto.Field( + proto.MESSAGE, + number=4, + oneof='image', + message='Intent.Message.Image', + ) + content_url = proto.Field( + proto.STRING, + number=5, + ) + + media_type = proto.Field( + proto.ENUM, + number=1, + enum='Intent.Message.MediaContent.ResponseMediaType', + ) + media_objects = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Intent.Message.MediaContent.ResponseMediaObject', + ) + + class BrowseCarouselCard(proto.Message): + r"""Browse Carousel Card for Actions on Google. + https://developers.google.com/actions/assistant/responses#browsing_carousel + + Attributes: + items (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem]): + Required. List of items in the Browse + Carousel Card. Minimum of two items, maximum of + ten. + image_display_options (google.cloud.dialogflow_v2.types.Intent.Message.BrowseCarouselCard.ImageDisplayOptions): + Optional. Settings for displaying the image. Applies to + every image in + [items][google.cloud.dialogflow.v2.Intent.Message.BrowseCarouselCard.items]. + """ + class ImageDisplayOptions(proto.Enum): + r"""Image display options for Actions on Google. This should be + used for when the image's aspect ratio does not match the image + container's aspect ratio. + """ + IMAGE_DISPLAY_OPTIONS_UNSPECIFIED = 0 + GRAY = 1 + WHITE = 2 + CROPPED = 3 + BLURRED_BACKGROUND = 4 + + class BrowseCarouselCardItem(proto.Message): + r"""Browsing carousel tile + + Attributes: + open_uri_action (google.cloud.dialogflow_v2.types.Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction): + Required. Action to present to the user. + title (str): + Required. Title of the carousel item. Maximum + of two lines of text. + description (str): + Optional. Description of the carousel item. + Maximum of four lines of text. + image (google.cloud.dialogflow_v2.types.Intent.Message.Image): + Optional. Hero image for the carousel item. + footer (str): + Optional. Text that appears at the bottom of + the Browse Carousel Card. Maximum of one line of + text. + """ + + class OpenUrlAction(proto.Message): + r"""Actions on Google action to open a given url. + + Attributes: + url (str): + Required. URL + url_type_hint (google.cloud.dialogflow_v2.types.Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction.UrlTypeHint): + Optional. Specifies the type of viewer that + is used when opening the URL. Defaults to + opening via web browser. + """ + class UrlTypeHint(proto.Enum): + r"""Type of the URI.""" + URL_TYPE_HINT_UNSPECIFIED = 0 + AMP_ACTION = 1 + AMP_CONTENT = 2 + + url = proto.Field( + proto.STRING, + number=1, + ) + url_type_hint = proto.Field( + proto.ENUM, + number=3, + enum='Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction.UrlTypeHint', + ) + + open_uri_action = proto.Field( + proto.MESSAGE, + number=1, + message='Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction', + ) + title = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + image = proto.Field( + proto.MESSAGE, + number=4, + message='Intent.Message.Image', + ) + footer = proto.Field( + proto.STRING, + number=5, + ) + + items = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem', + ) + image_display_options = proto.Field( + proto.ENUM, + number=2, + enum='Intent.Message.BrowseCarouselCard.ImageDisplayOptions', + ) + + class TableCard(proto.Message): + r"""Table card for Actions on Google. + + Attributes: + title (str): + Required. Title of the card. + subtitle (str): + Optional. Subtitle to the title. + image (google.cloud.dialogflow_v2.types.Intent.Message.Image): + Optional. Image which should be displayed on + the card. + column_properties (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.ColumnProperties]): + Optional. Display properties for the columns + in this table. + rows (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.TableCardRow]): + Optional. Rows in this table of data. + buttons (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.BasicCard.Button]): + Optional. List of buttons for the card. + """ + + title = proto.Field( + proto.STRING, + number=1, + ) + subtitle = proto.Field( + proto.STRING, + number=2, + ) + image = proto.Field( + proto.MESSAGE, + number=3, + message='Intent.Message.Image', + ) + column_properties = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Intent.Message.ColumnProperties', + ) + rows = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='Intent.Message.TableCardRow', + ) + buttons = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='Intent.Message.BasicCard.Button', + ) + + class ColumnProperties(proto.Message): + r"""Column properties for + [TableCard][google.cloud.dialogflow.v2.Intent.Message.TableCard]. + + Attributes: + header (str): + Required. Column heading. + horizontal_alignment (google.cloud.dialogflow_v2.types.Intent.Message.ColumnProperties.HorizontalAlignment): + Optional. Defines text alignment for all + cells in this column. + """ + class HorizontalAlignment(proto.Enum): + r"""Text alignments within a cell.""" + HORIZONTAL_ALIGNMENT_UNSPECIFIED = 0 + LEADING = 1 + CENTER = 2 + TRAILING = 3 + + header = proto.Field( + proto.STRING, + number=1, + ) + horizontal_alignment = proto.Field( + proto.ENUM, + number=2, + enum='Intent.Message.ColumnProperties.HorizontalAlignment', + ) + + class TableCardRow(proto.Message): + r"""Row of + [TableCard][google.cloud.dialogflow.v2.Intent.Message.TableCard]. + + Attributes: + cells (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.TableCardCell]): + Optional. List of cells that make up this + row. + divider_after (bool): + Optional. Whether to add a visual divider + after this row. + """ + + cells = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Intent.Message.TableCardCell', + ) + divider_after = proto.Field( + proto.BOOL, + number=2, + ) + + class TableCardCell(proto.Message): + r"""Cell of + [TableCardRow][google.cloud.dialogflow.v2.Intent.Message.TableCardRow]. + + Attributes: + text (str): + Required. Text in this cell. + """ + + text = proto.Field( + proto.STRING, + number=1, + ) + + text = proto.Field( + proto.MESSAGE, + number=1, + oneof='message', + message='Intent.Message.Text', + ) + image = proto.Field( + proto.MESSAGE, + number=2, + oneof='message', + message='Intent.Message.Image', + ) + quick_replies = proto.Field( + proto.MESSAGE, + number=3, + oneof='message', + message='Intent.Message.QuickReplies', + ) + card = proto.Field( + proto.MESSAGE, + number=4, + oneof='message', + message='Intent.Message.Card', + ) + payload = proto.Field( + proto.MESSAGE, + number=5, + oneof='message', + message=struct_pb2.Struct, + ) + simple_responses = proto.Field( + proto.MESSAGE, + number=7, + oneof='message', + message='Intent.Message.SimpleResponses', + ) + basic_card = proto.Field( + proto.MESSAGE, + number=8, + oneof='message', + message='Intent.Message.BasicCard', + ) + suggestions = proto.Field( + proto.MESSAGE, + number=9, + oneof='message', + message='Intent.Message.Suggestions', + ) + link_out_suggestion = proto.Field( + proto.MESSAGE, + number=10, + oneof='message', + message='Intent.Message.LinkOutSuggestion', + ) + list_select = proto.Field( + proto.MESSAGE, + number=11, + oneof='message', + message='Intent.Message.ListSelect', + ) + carousel_select = proto.Field( + proto.MESSAGE, + number=12, + oneof='message', + message='Intent.Message.CarouselSelect', + ) + browse_carousel_card = proto.Field( + proto.MESSAGE, + number=22, + oneof='message', + message='Intent.Message.BrowseCarouselCard', + ) + table_card = proto.Field( + proto.MESSAGE, + number=23, + oneof='message', + message='Intent.Message.TableCard', + ) + media_content = proto.Field( + proto.MESSAGE, + number=24, + oneof='message', + message='Intent.Message.MediaContent', + ) + platform = proto.Field( + proto.ENUM, + number=6, + enum='Intent.Message.Platform', + ) + + class FollowupIntentInfo(proto.Message): + r"""Represents a single followup intent in the chain. + + Attributes: + followup_intent_name (str): + The unique identifier of the followup intent. Format: + ``projects//agent/intents/``. + parent_followup_intent_name (str): + The unique identifier of the followup intent's parent. + Format: ``projects//agent/intents/``. + """ + + followup_intent_name = proto.Field( + proto.STRING, + number=1, + ) + parent_followup_intent_name = proto.Field( + proto.STRING, + number=2, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + webhook_state = proto.Field( + proto.ENUM, + number=6, + enum=WebhookState, + ) + priority = proto.Field( + proto.INT32, + number=3, + ) + is_fallback = proto.Field( + proto.BOOL, + number=4, + ) + ml_disabled = proto.Field( + proto.BOOL, + number=19, + ) + live_agent_handoff = proto.Field( + proto.BOOL, + number=20, + ) + end_interaction = proto.Field( + proto.BOOL, + number=21, + ) + input_context_names = proto.RepeatedField( + proto.STRING, + number=7, + ) + events = proto.RepeatedField( + proto.STRING, + number=8, + ) + training_phrases = proto.RepeatedField( + proto.MESSAGE, + number=9, + message=TrainingPhrase, + ) + action = proto.Field( + proto.STRING, + number=10, + ) + output_contexts = proto.RepeatedField( + proto.MESSAGE, + number=11, + message=context.Context, + ) + reset_contexts = proto.Field( + proto.BOOL, + number=12, + ) + parameters = proto.RepeatedField( + proto.MESSAGE, + number=13, + message=Parameter, + ) + messages = proto.RepeatedField( + proto.MESSAGE, + number=14, + message=Message, + ) + default_response_platforms = proto.RepeatedField( + proto.ENUM, + number=15, + enum=Message.Platform, + ) + root_followup_intent_name = proto.Field( + proto.STRING, + number=16, + ) + parent_followup_intent_name = proto.Field( + proto.STRING, + number=17, + ) + followup_intent_info = proto.RepeatedField( + proto.MESSAGE, + number=18, + message=FollowupIntentInfo, + ) + + +class ListIntentsRequest(proto.Message): + r"""The request message for + [Intents.ListIntents][google.cloud.dialogflow.v2.Intents.ListIntents]. + + Attributes: + parent (str): + Required. The agent to list all intents from. Format: + ``projects//agent`` or + ``projects//locations//agent``. + + Alternatively, you can specify the environment to list + intents for. Format: + ``projects//agent/environments/`` + or + ``projects//locations//agent/environments/``. + Note: training phrases of the intents will not be returned + for non-draft environment. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + intent_view (google.cloud.dialogflow_v2.types.IntentView): + Optional. The resource view to apply to the + returned intent. + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + intent_view = proto.Field( + proto.ENUM, + number=3, + enum='IntentView', + ) + page_size = proto.Field( + proto.INT32, + number=4, + ) + page_token = proto.Field( + proto.STRING, + number=5, + ) + + +class ListIntentsResponse(proto.Message): + r"""The response message for + [Intents.ListIntents][google.cloud.dialogflow.v2.Intents.ListIntents]. + + Attributes: + intents (Sequence[google.cloud.dialogflow_v2.types.Intent]): + The list of agent intents. There will be a maximum number of + items returned based on the page_size field in the request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + intents = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Intent', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetIntentRequest(proto.Message): + r"""The request message for + [Intents.GetIntent][google.cloud.dialogflow.v2.Intents.GetIntent]. + + Attributes: + name (str): + Required. The name of the intent. Format: + ``projects//agent/intents/``. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + intent_view (google.cloud.dialogflow_v2.types.IntentView): + Optional. The resource view to apply to the + returned intent. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + intent_view = proto.Field( + proto.ENUM, + number=3, + enum='IntentView', + ) + + +class CreateIntentRequest(proto.Message): + r"""The request message for + [Intents.CreateIntent][google.cloud.dialogflow.v2.Intents.CreateIntent]. + + Attributes: + parent (str): + Required. The agent to create a intent for. Format: + ``projects//agent``. + intent (google.cloud.dialogflow_v2.types.Intent): + Required. The intent to create. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + intent_view (google.cloud.dialogflow_v2.types.IntentView): + Optional. The resource view to apply to the + returned intent. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + intent = proto.Field( + proto.MESSAGE, + number=2, + message='Intent', + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + intent_view = proto.Field( + proto.ENUM, + number=4, + enum='IntentView', + ) + + +class UpdateIntentRequest(proto.Message): + r"""The request message for + [Intents.UpdateIntent][google.cloud.dialogflow.v2.Intents.UpdateIntent]. + + Attributes: + intent (google.cloud.dialogflow_v2.types.Intent): + Required. The intent to update. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which fields + get updated. + intent_view (google.cloud.dialogflow_v2.types.IntentView): + Optional. The resource view to apply to the + returned intent. + """ + + intent = proto.Field( + proto.MESSAGE, + number=1, + message='Intent', + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + intent_view = proto.Field( + proto.ENUM, + number=4, + enum='IntentView', + ) + + +class DeleteIntentRequest(proto.Message): + r"""The request message for + [Intents.DeleteIntent][google.cloud.dialogflow.v2.Intents.DeleteIntent]. + + Attributes: + name (str): + Required. The name of the intent to delete. If this intent + has direct or indirect followup intents, we also delete + them. Format: + ``projects//agent/intents/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class BatchUpdateIntentsRequest(proto.Message): + r""" + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The name of the agent to update or create intents + in. Format: ``projects//agent``. + intent_batch_uri (str): + The URI to a Google Cloud Storage file + containing intents to update or create. The file + format can either be a serialized proto (of + IntentBatch type) or JSON object. Note: The URI + must start with "gs://". + + This field is a member of `oneof`_ ``intent_batch``. + intent_batch_inline (google.cloud.dialogflow_v2.types.IntentBatch): + The collection of intents to update or + create. + + This field is a member of `oneof`_ ``intent_batch``. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which fields + get updated. + intent_view (google.cloud.dialogflow_v2.types.IntentView): + Optional. The resource view to apply to the + returned intent. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + intent_batch_uri = proto.Field( + proto.STRING, + number=2, + oneof='intent_batch', + ) + intent_batch_inline = proto.Field( + proto.MESSAGE, + number=3, + oneof='intent_batch', + message='IntentBatch', + ) + language_code = proto.Field( + proto.STRING, + number=4, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + intent_view = proto.Field( + proto.ENUM, + number=6, + enum='IntentView', + ) + + +class BatchUpdateIntentsResponse(proto.Message): + r"""The response message for + [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2.Intents.BatchUpdateIntents]. + + Attributes: + intents (Sequence[google.cloud.dialogflow_v2.types.Intent]): + The collection of updated or created intents. + """ + + intents = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Intent', + ) + + +class BatchDeleteIntentsRequest(proto.Message): + r"""The request message for + [Intents.BatchDeleteIntents][google.cloud.dialogflow.v2.Intents.BatchDeleteIntents]. + + Attributes: + parent (str): + Required. The name of the agent to delete all entities types + for. Format: ``projects//agent``. + intents (Sequence[google.cloud.dialogflow_v2.types.Intent]): + Required. The collection of intents to delete. Only intent + ``name`` must be filled in. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + intents = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Intent', + ) + + +class IntentBatch(proto.Message): + r"""This message is a wrapper around a collection of intents. + + Attributes: + intents (Sequence[google.cloud.dialogflow_v2.types.Intent]): + A collection of intents. + """ + + intents = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Intent', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/knowledge_base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/knowledge_base.py new file mode 100644 index 000000000..82e84c698 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/knowledge_base.py @@ -0,0 +1,258 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + 'KnowledgeBase', + 'ListKnowledgeBasesRequest', + 'ListKnowledgeBasesResponse', + 'GetKnowledgeBaseRequest', + 'CreateKnowledgeBaseRequest', + 'DeleteKnowledgeBaseRequest', + 'UpdateKnowledgeBaseRequest', + }, +) + + +class KnowledgeBase(proto.Message): + r"""A knowledge base represents a collection of knowledge documents that + you provide to Dialogflow. Your knowledge documents contain + information that may be useful during conversations with end-users. + Some Dialogflow features use knowledge bases when looking for a + response to an end-user input. + + For more information, see the `knowledge base + guide `__. + + Note: The ``projects.agent.knowledgeBases`` resource is deprecated; + only use ``projects.knowledgeBases``. + + Attributes: + name (str): + The knowledge base resource name. The name must be empty + when creating a knowledge base. Format: + ``projects//locations//knowledgeBases/``. + display_name (str): + Required. The display name of the knowledge + base. The name must be 1024 bytes or less; + otherwise, the creation request fails. + language_code (str): + Language which represents the KnowledgeBase. + When the KnowledgeBase is created/updated, + expect this to be present for non en-us + languages. When unspecified, the default + language code en-us applies. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + language_code = proto.Field( + proto.STRING, + number=4, + ) + + +class ListKnowledgeBasesRequest(proto.Message): + r"""Request message for + [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBases.ListKnowledgeBases]. + + Attributes: + parent (str): + Required. The project to list of knowledge bases for. + Format: ``projects//locations/``. + page_size (int): + The maximum number of items to return in a + single page. By default 10 and at most 100. + page_token (str): + The next_page_token value returned from a previous list + request. + filter (str): + The filter expression used to filter knowledge bases + returned by the list method. The expression has the + following syntax: + + [AND ] ... + + The following fields and operators are supported: + + - display_name with has(:) operator + - language_code with equals(=) operator + + Examples: + + - 'language_code=en-us' matches knowledge bases with en-us + language code. + - 'display_name:articles' matches knowledge bases whose + display name contains "articles". + - 'display_name:"Best Articles"' matches knowledge bases + whose display name contains "Best Articles". + - 'language_code=en-gb AND display_name=articles' matches + all knowledge bases whose display name contains + "articles" and whose language code is "en-gb". + + Note: An empty filter string (i.e. "") is a no-op and will + result in no filtering. + + For more information about filtering, see `API + Filtering `__. + """ + + 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 ListKnowledgeBasesResponse(proto.Message): + r"""Response message for + [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBases.ListKnowledgeBases]. + + Attributes: + knowledge_bases (Sequence[google.cloud.dialogflow_v2.types.KnowledgeBase]): + The list of knowledge bases. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + knowledge_bases = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='KnowledgeBase', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetKnowledgeBaseRequest(proto.Message): + r"""Request message for + [KnowledgeBases.GetKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.GetKnowledgeBase]. + + Attributes: + name (str): + Required. The name of the knowledge base to retrieve. Format + ``projects//locations//knowledgeBases/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateKnowledgeBaseRequest(proto.Message): + r"""Request message for + [KnowledgeBases.CreateKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.CreateKnowledgeBase]. + + Attributes: + parent (str): + Required. The project to create a knowledge base for. + Format: ``projects//locations/``. + knowledge_base (google.cloud.dialogflow_v2.types.KnowledgeBase): + Required. The knowledge base to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + knowledge_base = proto.Field( + proto.MESSAGE, + number=2, + message='KnowledgeBase', + ) + + +class DeleteKnowledgeBaseRequest(proto.Message): + r"""Request message for + [KnowledgeBases.DeleteKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.DeleteKnowledgeBase]. + + Attributes: + name (str): + Required. The name of the knowledge base to delete. Format: + ``projects//locations//knowledgeBases/``. + force (bool): + Optional. Force deletes the knowledge base. + When set to true, any documents in the knowledge + base are also deleted. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + force = proto.Field( + proto.BOOL, + number=2, + ) + + +class UpdateKnowledgeBaseRequest(proto.Message): + r"""Request message for + [KnowledgeBases.UpdateKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.UpdateKnowledgeBase]. + + Attributes: + knowledge_base (google.cloud.dialogflow_v2.types.KnowledgeBase): + Required. The knowledge base to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Not specified means ``update all``. Currently, + only ``display_name`` can be updated, an InvalidArgument + will be returned for attempting to update other fields. + """ + + knowledge_base = proto.Field( + proto.MESSAGE, + number=1, + message='KnowledgeBase', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/participant.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/participant.py new file mode 100644 index 000000000..1a66dbeb4 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/participant.py @@ -0,0 +1,968 @@ +# -*- 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.dialogflow_v2.types import audio_config +from google.cloud.dialogflow_v2.types import session +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + 'Participant', + 'Message', + 'CreateParticipantRequest', + 'GetParticipantRequest', + 'ListParticipantsRequest', + 'ListParticipantsResponse', + 'UpdateParticipantRequest', + 'AnalyzeContentRequest', + 'DtmfParameters', + 'AnalyzeContentResponse', + 'SuggestArticlesRequest', + 'SuggestArticlesResponse', + 'SuggestFaqAnswersRequest', + 'SuggestFaqAnswersResponse', + 'OutputAudio', + 'AutomatedAgentReply', + 'ArticleAnswer', + 'FaqAnswer', + 'SuggestionResult', + 'AnnotatedMessagePart', + 'MessageAnnotation', + 'AssistQueryParameters', + }, +) + + +class Participant(proto.Message): + r"""Represents a conversation participant (human agent, virtual + agent, end-user). + + Attributes: + name (str): + Optional. The unique identifier of this participant. Format: + ``projects//locations//conversations//participants/``. + role (google.cloud.dialogflow_v2.types.Participant.Role): + Immutable. The role this participant plays in + the conversation. This field must be set during + participant creation and is then immutable. + sip_recording_media_label (str): + Optional. Label applied to streams + representing this participant in SIPREC XML + metadata and SDP. This is used to assign + transcriptions from that media stream to this + participant. This field can be updated. + documents_metadata_filters (Sequence[google.cloud.dialogflow_v2.types.Participant.DocumentsMetadataFiltersEntry]): + Optional. Key-value filters on the metadata of documents + returned by article suggestion. If specified, article + suggestion only returns suggested documents that match all + filters in their + [Document.metadata][google.cloud.dialogflow.v2.Document.metadata]. + Multiple values for a metadata key should be concatenated by + comma. For example, filters to match all documents that have + 'US' or 'CA' in their market metadata values and 'agent' in + their user metadata values will be + + :: + + documents_metadata_filters { + key: "market" + value: "US,CA" + } + documents_metadata_filters { + key: "user" + value: "agent" + } + """ + class Role(proto.Enum): + r"""Enumeration of the roles a participant can play in a + conversation. + """ + ROLE_UNSPECIFIED = 0 + HUMAN_AGENT = 1 + AUTOMATED_AGENT = 2 + END_USER = 3 + + name = proto.Field( + proto.STRING, + number=1, + ) + role = proto.Field( + proto.ENUM, + number=2, + enum=Role, + ) + sip_recording_media_label = proto.Field( + proto.STRING, + number=6, + ) + documents_metadata_filters = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + + +class Message(proto.Message): + r"""Represents a message posted into a conversation. + + Attributes: + name (str): + The unique identifier of the message. Format: + ``projects//locations//conversations//messages/``. + content (str): + Required. The message content. + language_code (str): + Optional. The message language. This should be a + `BCP-47 `__ + language tag. Example: "en-US". + participant (str): + Output only. The participant that sends this + message. + participant_role (google.cloud.dialogflow_v2.types.Participant.Role): + Output only. The role of the participant. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the message was + created. + message_annotation (google.cloud.dialogflow_v2.types.MessageAnnotation): + Output only. The annotation for the message. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + content = proto.Field( + proto.STRING, + number=2, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + participant = proto.Field( + proto.STRING, + number=4, + ) + participant_role = proto.Field( + proto.ENUM, + number=5, + enum='Participant.Role', + ) + create_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + message_annotation = proto.Field( + proto.MESSAGE, + number=7, + message='MessageAnnotation', + ) + + +class CreateParticipantRequest(proto.Message): + r"""The request message for + [Participants.CreateParticipant][google.cloud.dialogflow.v2.Participants.CreateParticipant]. + + Attributes: + parent (str): + Required. Resource identifier of the conversation adding the + participant. Format: + ``projects//locations//conversations/``. + participant (google.cloud.dialogflow_v2.types.Participant): + Required. The participant to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + participant = proto.Field( + proto.MESSAGE, + number=2, + message='Participant', + ) + + +class GetParticipantRequest(proto.Message): + r"""The request message for + [Participants.GetParticipant][google.cloud.dialogflow.v2.Participants.GetParticipant]. + + Attributes: + name (str): + Required. The name of the participant. Format: + ``projects//locations//conversations//participants/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListParticipantsRequest(proto.Message): + r"""The request message for + [Participants.ListParticipants][google.cloud.dialogflow.v2.Participants.ListParticipants]. + + Attributes: + parent (str): + Required. The conversation to list all participants from. + Format: + ``projects//locations//conversations/``. + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListParticipantsResponse(proto.Message): + r"""The response message for + [Participants.ListParticipants][google.cloud.dialogflow.v2.Participants.ListParticipants]. + + Attributes: + participants (Sequence[google.cloud.dialogflow_v2.types.Participant]): + The list of participants. There is a maximum number of items + returned based on the page_size field in the request. + next_page_token (str): + Token to retrieve the next page of results or + empty if there are no more results in the list. + """ + + @property + def raw_page(self): + return self + + participants = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Participant', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateParticipantRequest(proto.Message): + r"""The request message for + [Participants.UpdateParticipant][google.cloud.dialogflow.v2.Participants.UpdateParticipant]. + + Attributes: + participant (google.cloud.dialogflow_v2.types.Participant): + Required. The participant to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to specify which fields to + update. + """ + + participant = proto.Field( + proto.MESSAGE, + number=1, + message='Participant', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class AnalyzeContentRequest(proto.Message): + r"""The request message for + [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + participant (str): + Required. The name of the participant this text comes from. + Format: + ``projects//locations//conversations//participants/``. + text_input (google.cloud.dialogflow_v2.types.TextInput): + The natural language text to be processed. + + This field is a member of `oneof`_ ``input``. + event_input (google.cloud.dialogflow_v2.types.EventInput): + An input event to send to Dialogflow. + + This field is a member of `oneof`_ ``input``. + reply_audio_config (google.cloud.dialogflow_v2.types.OutputAudioConfig): + Speech synthesis configuration. + The speech synthesis settings for a virtual + agent that may be configured for the associated + conversation profile are not used when calling + AnalyzeContent. If this configuration is not + supplied, speech synthesis is disabled. + query_params (google.cloud.dialogflow_v2.types.QueryParameters): + Parameters for a Dialogflow virtual-agent + query. + assist_query_params (google.cloud.dialogflow_v2.types.AssistQueryParameters): + Parameters for a human assist query. + request_id (str): + A unique identifier for this request. Restricted to 36 ASCII + characters. A random UUID is recommended. This request is + only idempotent if a ``request_id`` is provided. + """ + + participant = proto.Field( + proto.STRING, + number=1, + ) + text_input = proto.Field( + proto.MESSAGE, + number=6, + oneof='input', + message=session.TextInput, + ) + event_input = proto.Field( + proto.MESSAGE, + number=8, + oneof='input', + message=session.EventInput, + ) + reply_audio_config = proto.Field( + proto.MESSAGE, + number=5, + message=audio_config.OutputAudioConfig, + ) + query_params = proto.Field( + proto.MESSAGE, + number=9, + message=session.QueryParameters, + ) + assist_query_params = proto.Field( + proto.MESSAGE, + number=14, + message='AssistQueryParameters', + ) + request_id = proto.Field( + proto.STRING, + number=11, + ) + + +class DtmfParameters(proto.Message): + r"""The message in the response that indicates the parameters of + DTMF. + + Attributes: + accepts_dtmf_input (bool): + Indicates whether DTMF input can be handled + in the next request. + """ + + accepts_dtmf_input = proto.Field( + proto.BOOL, + number=1, + ) + + +class AnalyzeContentResponse(proto.Message): + r"""The response message for + [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]. + + Attributes: + reply_text (str): + The output text content. + This field is set if the automated agent + responded with text to show to the user. + reply_audio (google.cloud.dialogflow_v2.types.OutputAudio): + The audio data bytes encoded as specified in the request. + This field is set if: + + - ``reply_audio_config`` was specified in the request, or + - The automated agent responded with audio to play to the + user. In such case, ``reply_audio.config`` contains + settings used to synthesize the speech. + + In some scenarios, multiple output audio fields may be + present in the response structure. In these cases, only the + top-most-level audio output has content. + automated_agent_reply (google.cloud.dialogflow_v2.types.AutomatedAgentReply): + Only set if a Dialogflow automated agent has responded. Note + that: + [AutomatedAgentReply.detect_intent_response.output_audio][] + and + [AutomatedAgentReply.detect_intent_response.output_audio_config][] + are always empty, use + [reply_audio][google.cloud.dialogflow.v2.AnalyzeContentResponse.reply_audio] + instead. + message (google.cloud.dialogflow_v2.types.Message): + Message analyzed by CCAI. + human_agent_suggestion_results (Sequence[google.cloud.dialogflow_v2.types.SuggestionResult]): + The suggestions for most recent human agent. The order is + the same as + [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] + of + [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config]. + end_user_suggestion_results (Sequence[google.cloud.dialogflow_v2.types.SuggestionResult]): + The suggestions for end user. The order is the same as + [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] + of + [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config]. + dtmf_parameters (google.cloud.dialogflow_v2.types.DtmfParameters): + Indicates the parameters of DTMF. + """ + + reply_text = proto.Field( + proto.STRING, + number=1, + ) + reply_audio = proto.Field( + proto.MESSAGE, + number=2, + message='OutputAudio', + ) + automated_agent_reply = proto.Field( + proto.MESSAGE, + number=3, + message='AutomatedAgentReply', + ) + message = proto.Field( + proto.MESSAGE, + number=5, + message='Message', + ) + human_agent_suggestion_results = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='SuggestionResult', + ) + end_user_suggestion_results = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='SuggestionResult', + ) + dtmf_parameters = proto.Field( + proto.MESSAGE, + number=9, + message='DtmfParameters', + ) + + +class SuggestArticlesRequest(proto.Message): + r"""The request message for + [Participants.SuggestArticles][google.cloud.dialogflow.v2.Participants.SuggestArticles]. + + Attributes: + parent (str): + Required. The name of the participant to fetch suggestion + for. Format: + ``projects//locations//conversations//participants/``. + latest_message (str): + The name of the latest conversation message to compile + suggestion for. If empty, it will be the latest message of + the conversation. + + Format: + ``projects//locations//conversations//messages/``. + context_size (int): + Max number of messages prior to and including + [latest_message][google.cloud.dialogflow.v2.SuggestArticlesRequest.latest_message] + to use as context when compiling the suggestion. By default + 20 and at most 50. + assist_query_params (google.cloud.dialogflow_v2.types.AssistQueryParameters): + Parameters for a human assist query. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + latest_message = proto.Field( + proto.STRING, + number=2, + ) + context_size = proto.Field( + proto.INT32, + number=3, + ) + assist_query_params = proto.Field( + proto.MESSAGE, + number=4, + message='AssistQueryParameters', + ) + + +class SuggestArticlesResponse(proto.Message): + r"""The response message for + [Participants.SuggestArticles][google.cloud.dialogflow.v2.Participants.SuggestArticles]. + + Attributes: + article_answers (Sequence[google.cloud.dialogflow_v2.types.ArticleAnswer]): + Articles ordered by score in descending + order. + latest_message (str): + The name of the latest conversation message used to compile + suggestion for. + + Format: + ``projects//locations//conversations//messages/``. + context_size (int): + Number of messages prior to and including + [latest_message][google.cloud.dialogflow.v2.SuggestArticlesResponse.latest_message] + to compile the suggestion. It may be smaller than the + [SuggestArticlesRequest.context_size][google.cloud.dialogflow.v2.SuggestArticlesRequest.context_size] + field in the request if there aren't that many messages in + the conversation. + """ + + article_answers = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ArticleAnswer', + ) + latest_message = proto.Field( + proto.STRING, + number=2, + ) + context_size = proto.Field( + proto.INT32, + number=3, + ) + + +class SuggestFaqAnswersRequest(proto.Message): + r"""The request message for + [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2.Participants.SuggestFaqAnswers]. + + Attributes: + parent (str): + Required. The name of the participant to fetch suggestion + for. Format: + ``projects//locations//conversations//participants/``. + latest_message (str): + The name of the latest conversation message to compile + suggestion for. If empty, it will be the latest message of + the conversation. + + Format: + ``projects//locations//conversations//messages/``. + context_size (int): + Max number of messages prior to and including + [latest_message] to use as context when compiling the + suggestion. By default 20 and at most 50. + assist_query_params (google.cloud.dialogflow_v2.types.AssistQueryParameters): + Parameters for a human assist query. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + latest_message = proto.Field( + proto.STRING, + number=2, + ) + context_size = proto.Field( + proto.INT32, + number=3, + ) + assist_query_params = proto.Field( + proto.MESSAGE, + number=4, + message='AssistQueryParameters', + ) + + +class SuggestFaqAnswersResponse(proto.Message): + r"""The request message for + [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2.Participants.SuggestFaqAnswers]. + + Attributes: + faq_answers (Sequence[google.cloud.dialogflow_v2.types.FaqAnswer]): + Answers extracted from FAQ documents. + latest_message (str): + The name of the latest conversation message used to compile + suggestion for. + + Format: + ``projects//locations//conversations//messages/``. + context_size (int): + Number of messages prior to and including + [latest_message][google.cloud.dialogflow.v2.SuggestFaqAnswersResponse.latest_message] + to compile the suggestion. It may be smaller than the + [SuggestFaqAnswersRequest.context_size][google.cloud.dialogflow.v2.SuggestFaqAnswersRequest.context_size] + field in the request if there aren't that many messages in + the conversation. + """ + + faq_answers = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='FaqAnswer', + ) + latest_message = proto.Field( + proto.STRING, + number=2, + ) + context_size = proto.Field( + proto.INT32, + number=3, + ) + + +class OutputAudio(proto.Message): + r"""Represents the natural language speech audio to be played to + the end user. + + Attributes: + config (google.cloud.dialogflow_v2.types.OutputAudioConfig): + Instructs the speech synthesizer how to + generate the speech audio. + audio (bytes): + The natural language speech audio. + """ + + config = proto.Field( + proto.MESSAGE, + number=1, + message=audio_config.OutputAudioConfig, + ) + audio = proto.Field( + proto.BYTES, + number=2, + ) + + +class AutomatedAgentReply(proto.Message): + r"""Represents a response from an automated agent. + + Attributes: + detect_intent_response (google.cloud.dialogflow_v2.types.DetectIntentResponse): + Response of the Dialogflow + [Sessions.DetectIntent][google.cloud.dialogflow.v2.Sessions.DetectIntent] + call. + automated_agent_reply_type (google.cloud.dialogflow_v2.types.AutomatedAgentReply.AutomatedAgentReplyType): + AutomatedAgentReply type. + allow_cancellation (bool): + Indicates whether the partial automated agent + reply is interruptible when a later reply + message arrives. e.g. if the agent specified + some music as partial response, it can be + cancelled. + """ + class AutomatedAgentReplyType(proto.Enum): + r"""Represents different automated agent reply types.""" + AUTOMATED_AGENT_REPLY_TYPE_UNSPECIFIED = 0 + PARTIAL = 1 + FINAL = 2 + + detect_intent_response = proto.Field( + proto.MESSAGE, + number=1, + message=session.DetectIntentResponse, + ) + automated_agent_reply_type = proto.Field( + proto.ENUM, + number=7, + enum=AutomatedAgentReplyType, + ) + allow_cancellation = proto.Field( + proto.BOOL, + number=8, + ) + + +class ArticleAnswer(proto.Message): + r"""Represents article answer. + + Attributes: + title (str): + The article title. + uri (str): + The article URI. + snippets (Sequence[str]): + Article snippets. + confidence (float): + Article match confidence. + The system's confidence score that this article + is a good match for this conversation, as a + value from 0.0 (completely uncertain) to 1.0 + (completely certain). + metadata (Sequence[google.cloud.dialogflow_v2.types.ArticleAnswer.MetadataEntry]): + A map that contains metadata about the answer + and the document from which it originates. + answer_record (str): + The name of answer record, in the format of + "projects//locations//answerRecords/". + """ + + title = proto.Field( + proto.STRING, + number=1, + ) + uri = proto.Field( + proto.STRING, + number=2, + ) + snippets = proto.RepeatedField( + proto.STRING, + number=3, + ) + confidence = proto.Field( + proto.FLOAT, + number=4, + ) + metadata = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + answer_record = proto.Field( + proto.STRING, + number=6, + ) + + +class FaqAnswer(proto.Message): + r"""Represents answer from "frequently asked questions". + + Attributes: + answer (str): + The piece of text from the ``source`` knowledge base + document. + confidence (float): + The system's confidence score that this + Knowledge answer is a good match for this + conversational query, range from 0.0 (completely + uncertain) to 1.0 (completely certain). + question (str): + The corresponding FAQ question. + source (str): + Indicates which Knowledge Document this answer was extracted + from. Format: + ``projects//locations//agent/knowledgeBases//documents/``. + metadata (Sequence[google.cloud.dialogflow_v2.types.FaqAnswer.MetadataEntry]): + A map that contains metadata about the answer + and the document from which it originates. + answer_record (str): + The name of answer record, in the format of + "projects//locations//answerRecords/". + """ + + answer = proto.Field( + proto.STRING, + number=1, + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + question = proto.Field( + proto.STRING, + number=3, + ) + source = proto.Field( + proto.STRING, + number=4, + ) + metadata = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + answer_record = proto.Field( + proto.STRING, + number=6, + ) + + +class SuggestionResult(proto.Message): + r"""One response of different type of suggestion response which is used + in the response of + [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent] + and + [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent], + as well as + [HumanAgentAssistantEvent][google.cloud.dialogflow.v2.HumanAgentAssistantEvent]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + error (google.rpc.status_pb2.Status): + Error status if the request failed. + + This field is a member of `oneof`_ ``suggestion_response``. + suggest_articles_response (google.cloud.dialogflow_v2.types.SuggestArticlesResponse): + SuggestArticlesResponse if request is for + ARTICLE_SUGGESTION. + + This field is a member of `oneof`_ ``suggestion_response``. + suggest_faq_answers_response (google.cloud.dialogflow_v2.types.SuggestFaqAnswersResponse): + SuggestFaqAnswersResponse if request is for FAQ_ANSWER. + + This field is a member of `oneof`_ ``suggestion_response``. + """ + + error = proto.Field( + proto.MESSAGE, + number=1, + oneof='suggestion_response', + message=status_pb2.Status, + ) + suggest_articles_response = proto.Field( + proto.MESSAGE, + number=2, + oneof='suggestion_response', + message='SuggestArticlesResponse', + ) + suggest_faq_answers_response = proto.Field( + proto.MESSAGE, + number=3, + oneof='suggestion_response', + message='SuggestFaqAnswersResponse', + ) + + +class AnnotatedMessagePart(proto.Message): + r"""Represents a part of a message possibly annotated with an + entity. The part can be an entity or purely a part of the + message between two entities or message start/end. + + Attributes: + text (str): + A part of a message possibly annotated with + an entity. + entity_type (str): + The `Dialogflow system entity + type `__ + of this message part. If this is empty, Dialogflow could not + annotate the phrase part with a system entity. + formatted_value (google.protobuf.struct_pb2.Value): + The `Dialogflow system entity formatted + value `__ + of this message part. For example for a system entity of + type ``@sys.unit-currency``, this may contain: + + .. raw:: html + +
+                {
+                  "amount": 5,
+                  "currency": "USD"
+                }
+                
+ """ + + text = proto.Field( + proto.STRING, + number=1, + ) + entity_type = proto.Field( + proto.STRING, + number=2, + ) + formatted_value = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Value, + ) + + +class MessageAnnotation(proto.Message): + r"""Represents the result of annotation for the message. + + Attributes: + parts (Sequence[google.cloud.dialogflow_v2.types.AnnotatedMessagePart]): + The collection of annotated message parts ordered by their + position in the message. You can recover the annotated + message by concatenating [AnnotatedMessagePart.text]. + contain_entities (bool): + Indicates whether the text message contains + entities. + """ + + parts = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AnnotatedMessagePart', + ) + contain_entities = proto.Field( + proto.BOOL, + number=2, + ) + + +class AssistQueryParameters(proto.Message): + r"""Represents the parameters of human assist query. + + Attributes: + documents_metadata_filters (Sequence[google.cloud.dialogflow_v2.types.AssistQueryParameters.DocumentsMetadataFiltersEntry]): + Key-value filters on the metadata of documents returned by + article suggestion. If specified, article suggestion only + returns suggested documents that match all filters in their + [Document.metadata][google.cloud.dialogflow.v2.Document.metadata]. + Multiple values for a metadata key should be concatenated by + comma. For example, filters to match all documents that have + 'US' or 'CA' in their market metadata values and 'agent' in + their user metadata values will be + + :: + + documents_metadata_filters { + key: "market" + value: "US,CA" + } + documents_metadata_filters { + key: "user" + value: "agent" + } + """ + + documents_metadata_filters = proto.MapField( + proto.STRING, + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/session.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/session.py new file mode 100644 index 000000000..bf8398095 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/session.py @@ -0,0 +1,1004 @@ +# -*- 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.dialogflow_v2.types import audio_config as gcd_audio_config +from google.cloud.dialogflow_v2.types import context +from google.cloud.dialogflow_v2.types import intent as gcd_intent +from google.cloud.dialogflow_v2.types import session_entity_type +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + 'DetectIntentRequest', + 'DetectIntentResponse', + 'QueryParameters', + 'QueryInput', + 'QueryResult', + 'StreamingDetectIntentRequest', + 'StreamingDetectIntentResponse', + 'StreamingRecognitionResult', + 'TextInput', + 'EventInput', + 'SentimentAnalysisRequestConfig', + 'SentimentAnalysisResult', + 'Sentiment', + }, +) + + +class DetectIntentRequest(proto.Message): + r"""The request to detect user's intent. + + Attributes: + session (str): + Required. The name of the session this query is sent to. + Format: + ``projects//agent/sessions/``, or + ``projects//agent/environments//users//sessions/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment (``Environment ID`` might be referred to + as environment name at some places). If ``User ID`` is not + specified, we are using "-". It's up to the API caller to + choose an appropriate ``Session ID`` and ``User Id``. They + can be a random number or some type of user and session + identifiers (preferably hashed). The length of the + ``Session ID`` and ``User ID`` must not exceed 36 + characters. + + For more information, see the `API interactions + guide `__. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + query_params (google.cloud.dialogflow_v2.types.QueryParameters): + The parameters of this query. + query_input (google.cloud.dialogflow_v2.types.QueryInput): + Required. The input specification. It can be + set to: + 1. an audio config + which instructs the speech recognizer how to + process the speech audio, + 2. a conversational query in the form of text, + or + 3. an event that specifies which intent to + trigger. + output_audio_config (google.cloud.dialogflow_v2.types.OutputAudioConfig): + Instructs the speech synthesizer how to + generate the output audio. If this field is not + set and agent-level speech synthesizer is not + configured, no output audio is generated. + output_audio_config_mask (google.protobuf.field_mask_pb2.FieldMask): + Mask for + [output_audio_config][google.cloud.dialogflow.v2.DetectIntentRequest.output_audio_config] + indicating which settings in this request-level config + should override speech synthesizer settings defined at + agent-level. + + If unspecified or empty, + [output_audio_config][google.cloud.dialogflow.v2.DetectIntentRequest.output_audio_config] + replaces the agent-level config in its entirety. + input_audio (bytes): + The natural language speech audio to be processed. This + field should be populated iff ``query_input`` is set to an + input audio config. A single request can contain up to 1 + minute of speech audio data. + """ + + session = proto.Field( + proto.STRING, + number=1, + ) + query_params = proto.Field( + proto.MESSAGE, + number=2, + message='QueryParameters', + ) + query_input = proto.Field( + proto.MESSAGE, + number=3, + message='QueryInput', + ) + output_audio_config = proto.Field( + proto.MESSAGE, + number=4, + message=gcd_audio_config.OutputAudioConfig, + ) + output_audio_config_mask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + input_audio = proto.Field( + proto.BYTES, + number=5, + ) + + +class DetectIntentResponse(proto.Message): + r"""The message returned from the DetectIntent method. + + Attributes: + response_id (str): + The unique identifier of the response. It can + be used to locate a response in the training + example set or for reporting issues. + query_result (google.cloud.dialogflow_v2.types.QueryResult): + The selected results of the conversational query or event + processing. See ``alternative_query_results`` for additional + potential results. + webhook_status (google.rpc.status_pb2.Status): + Specifies the status of the webhook request. + output_audio (bytes): + The audio data bytes encoded as specified in the request. + Note: The output audio is generated based on the values of + default platform text responses found in the + ``query_result.fulfillment_messages`` field. If multiple + default text responses exist, they will be concatenated when + generating audio. If no default platform text responses + exist, the generated audio content will be empty. + + In some scenarios, multiple output audio fields may be + present in the response structure. In these cases, only the + top-most-level audio output has content. + output_audio_config (google.cloud.dialogflow_v2.types.OutputAudioConfig): + The config used by the speech synthesizer to + generate the output audio. + """ + + response_id = proto.Field( + proto.STRING, + number=1, + ) + query_result = proto.Field( + proto.MESSAGE, + number=2, + message='QueryResult', + ) + webhook_status = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + output_audio = proto.Field( + proto.BYTES, + number=4, + ) + output_audio_config = proto.Field( + proto.MESSAGE, + number=6, + message=gcd_audio_config.OutputAudioConfig, + ) + + +class QueryParameters(proto.Message): + r"""Represents the parameters of the conversational query. + + Attributes: + time_zone (str): + The time zone of this conversational query from the `time + zone database `__, e.g., + America/New_York, Europe/Paris. If not provided, the time + zone specified in agent settings is used. + geo_location (google.type.latlng_pb2.LatLng): + The geo location of this conversational + query. + contexts (Sequence[google.cloud.dialogflow_v2.types.Context]): + The collection of contexts to be activated + before this query is executed. + reset_contexts (bool): + Specifies whether to delete all contexts in + the current session before the new ones are + activated. + session_entity_types (Sequence[google.cloud.dialogflow_v2.types.SessionEntityType]): + Additional session entity types to replace or + extend developer entity types with. The entity + synonyms apply to all languages and persist for + the session of this query. + payload (google.protobuf.struct_pb2.Struct): + This field can be used to pass custom data to your webhook. + Arbitrary JSON objects are supported. If supplied, the value + is used to populate the + ``WebhookRequest.original_detect_intent_request.payload`` + field sent to your webhook. + sentiment_analysis_request_config (google.cloud.dialogflow_v2.types.SentimentAnalysisRequestConfig): + Configures the type of sentiment analysis to + perform. If not provided, sentiment analysis is + not performed. + webhook_headers (Sequence[google.cloud.dialogflow_v2.types.QueryParameters.WebhookHeadersEntry]): + This field can be used to pass HTTP headers + for a webhook call. These headers will be sent + to webhook along with the headers that have been + configured through the Dialogflow web console. + The headers defined within this field will + overwrite the headers configured through the + Dialogflow console if there is a conflict. + Header names are case-insensitive. Google's + specified headers are not allowed. Including: + "Host", "Content-Length", "Connection", "From", + "User-Agent", "Accept-Encoding", "If-Modified- + Since", "If-None-Match", "X-Forwarded-For", etc. + """ + + time_zone = proto.Field( + proto.STRING, + number=1, + ) + geo_location = proto.Field( + proto.MESSAGE, + number=2, + message=latlng_pb2.LatLng, + ) + contexts = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=context.Context, + ) + reset_contexts = proto.Field( + proto.BOOL, + number=4, + ) + session_entity_types = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=session_entity_type.SessionEntityType, + ) + payload = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + sentiment_analysis_request_config = proto.Field( + proto.MESSAGE, + number=10, + message='SentimentAnalysisRequestConfig', + ) + webhook_headers = proto.MapField( + proto.STRING, + proto.STRING, + number=14, + ) + + +class QueryInput(proto.Message): + r"""Represents the query input. It can contain either: + 1. An audio config which + instructs the speech recognizer how to process the speech + audio. + 2. A conversational query in the form of text,. + + 3. An event that specifies which intent to trigger. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + audio_config (google.cloud.dialogflow_v2.types.InputAudioConfig): + Instructs the speech recognizer how to + process the speech audio. + + This field is a member of `oneof`_ ``input``. + text (google.cloud.dialogflow_v2.types.TextInput): + The natural language text to be processed. + + This field is a member of `oneof`_ ``input``. + event (google.cloud.dialogflow_v2.types.EventInput): + The event to be processed. + + This field is a member of `oneof`_ ``input``. + """ + + audio_config = proto.Field( + proto.MESSAGE, + number=1, + oneof='input', + message=gcd_audio_config.InputAudioConfig, + ) + text = proto.Field( + proto.MESSAGE, + number=2, + oneof='input', + message='TextInput', + ) + event = proto.Field( + proto.MESSAGE, + number=3, + oneof='input', + message='EventInput', + ) + + +class QueryResult(proto.Message): + r"""Represents the result of conversational query or event + processing. + + Attributes: + query_text (str): + The original conversational query text: + + - If natural language text was provided as input, + ``query_text`` contains a copy of the input. + - If natural language speech audio was provided as input, + ``query_text`` contains the speech recognition result. If + speech recognizer produced multiple alternatives, a + particular one is picked. + - If automatic spell correction is enabled, ``query_text`` + will contain the corrected user input. + language_code (str): + The language that was triggered during intent detection. See + `Language + Support `__ + for a list of the currently supported language codes. + speech_recognition_confidence (float): + The Speech recognition confidence between 0.0 + and 1.0. A higher number indicates an estimated + greater likelihood that the recognized words are + correct. The default of 0.0 is a sentinel value + indicating that confidence was not set. + + This field is not guaranteed to be accurate or + set. In particular this field isn't set for + StreamingDetectIntent since the streaming + endpoint has separate confidence estimates per + portion of the audio in + StreamingRecognitionResult. + action (str): + The action name from the matched intent. + parameters (google.protobuf.struct_pb2.Struct): + The collection of extracted parameters. + Depending on your protocol or client library + language, this is a map, associative array, + symbol table, dictionary, or JSON object + composed of a collection of (MapKey, MapValue) + pairs: + - MapKey type: string + - MapKey value: parameter name + - MapValue type: + - If parameter's entity type is a + composite entity: map - Else: depending on + parameter value type, could be one of string, + number, boolean, null, list or map + - MapValue value: + - If parameter's entity type is a + composite entity: map from composite + entity property names to property values - + Else: parameter value + all_required_params_present (bool): + This field is set to: + + - ``false`` if the matched intent has required parameters + and not all of the required parameter values have been + collected. + - ``true`` if all required parameter values have been + collected, or if the matched intent doesn't contain any + required parameters. + cancels_slot_filling (bool): + Indicates whether the conversational query + triggers a cancellation for slot filling. + fulfillment_text (str): + The text to be pronounced to the user or shown on the + screen. Note: This is a legacy field, + ``fulfillment_messages`` should be preferred. + fulfillment_messages (Sequence[google.cloud.dialogflow_v2.types.Intent.Message]): + The collection of rich messages to present to + the user. + webhook_source (str): + If the query was fulfilled by a webhook call, this field is + set to the value of the ``source`` field returned in the + webhook response. + webhook_payload (google.protobuf.struct_pb2.Struct): + If the query was fulfilled by a webhook call, this field is + set to the value of the ``payload`` field returned in the + webhook response. + output_contexts (Sequence[google.cloud.dialogflow_v2.types.Context]): + The collection of output contexts. If applicable, + ``output_contexts.parameters`` contains entries with name + ``.original`` containing the original + parameter values before the query. + intent (google.cloud.dialogflow_v2.types.Intent): + The intent that matched the conversational query. Some, not + all fields are filled in this message, including but not + limited to: ``name``, ``display_name``, ``end_interaction`` + and ``is_fallback``. + intent_detection_confidence (float): + The intent detection confidence. Values range from 0.0 + (completely uncertain) to 1.0 (completely certain). This + value is for informational purpose only and is only used to + help match the best intent within the classification + threshold. This value may change for the same end-user + expression at any time due to a model retraining or change + in implementation. If there are + ``multiple knowledge_answers`` messages, this value is set + to the greatest ``knowledgeAnswers.match_confidence`` value + in the list. + diagnostic_info (google.protobuf.struct_pb2.Struct): + Free-form diagnostic information for the + associated detect intent request. The fields of + this data can change without notice, so you + should not write code that depends on its + structure. + The data may contain: + + - webhook call latency + - webhook errors + sentiment_analysis_result (google.cloud.dialogflow_v2.types.SentimentAnalysisResult): + The sentiment analysis result, which depends on the + ``sentiment_analysis_request_config`` specified in the + request. + """ + + query_text = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=15, + ) + speech_recognition_confidence = proto.Field( + proto.FLOAT, + number=2, + ) + action = proto.Field( + proto.STRING, + number=3, + ) + parameters = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Struct, + ) + all_required_params_present = proto.Field( + proto.BOOL, + number=5, + ) + cancels_slot_filling = proto.Field( + proto.BOOL, + number=21, + ) + fulfillment_text = proto.Field( + proto.STRING, + number=6, + ) + fulfillment_messages = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=gcd_intent.Intent.Message, + ) + webhook_source = proto.Field( + proto.STRING, + number=8, + ) + webhook_payload = proto.Field( + proto.MESSAGE, + number=9, + message=struct_pb2.Struct, + ) + output_contexts = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=context.Context, + ) + intent = proto.Field( + proto.MESSAGE, + number=11, + message=gcd_intent.Intent, + ) + intent_detection_confidence = proto.Field( + proto.FLOAT, + number=12, + ) + diagnostic_info = proto.Field( + proto.MESSAGE, + number=14, + message=struct_pb2.Struct, + ) + sentiment_analysis_result = proto.Field( + proto.MESSAGE, + number=17, + message='SentimentAnalysisResult', + ) + + +class StreamingDetectIntentRequest(proto.Message): + r"""The top-level message sent by the client to the + [Sessions.StreamingDetectIntent][google.cloud.dialogflow.v2.Sessions.StreamingDetectIntent] + method. + + Multiple request messages should be sent in order: + + 1. The first message must contain + [session][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.session], + [query_input][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_input] + plus optionally + [query_params][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_params]. + If the client wants to receive an audio response, it should also + contain + [output_audio_config][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.output_audio_config]. + The message must not contain + [input_audio][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.input_audio]. + + 2. If + [query_input][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_input] + was set to + [query_input.audio_config][google.cloud.dialogflow.v2.InputAudioConfig], + all subsequent messages must contain + [input_audio][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.input_audio] + to continue with Speech recognition. If you decide to rather + detect an intent from text input after you already started Speech + recognition, please send a message with + [query_input.text][google.cloud.dialogflow.v2.QueryInput.text]. + + However, note that: + + - Dialogflow will bill you for the audio duration so far. + - Dialogflow discards all Speech recognition results in favor of + the input text. + - Dialogflow will use the language code from the first message. + + After you sent all input, you must half-close or abort the request + stream. + + Attributes: + session (str): + Required. The name of the session the query is sent to. + Format of the session name: + ``projects//agent/sessions/``, or + ``projects//agent/environments//users//sessions/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. If ``User ID`` is not specified, we are + using "-". It's up to the API caller to choose an + appropriate ``Session ID`` and ``User Id``. They can be a + random number or some type of user and session identifiers + (preferably hashed). The length of the ``Session ID`` and + ``User ID`` must not exceed 36 characters. + + For more information, see the `API interactions + guide `__. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + query_params (google.cloud.dialogflow_v2.types.QueryParameters): + The parameters of this query. + query_input (google.cloud.dialogflow_v2.types.QueryInput): + Required. The input specification. It can be + set to: + 1. an audio config which instructs the speech + recognizer how to process the speech audio, + + 2. a conversational query in the form of text, + or + 3. an event that specifies which intent to + trigger. + single_utterance (bool): + Please use + [InputAudioConfig.single_utterance][google.cloud.dialogflow.v2.InputAudioConfig.single_utterance] + instead. If ``false`` (default), recognition does not cease + until the client closes the stream. If ``true``, the + recognizer will detect a single spoken utterance in input + audio. Recognition ceases when it detects the audio's voice + has stopped or paused. In this case, once a detected intent + is received, the client should close the stream and start a + new request with a new stream as needed. This setting is + ignored when ``query_input`` is a piece of text or an event. + output_audio_config (google.cloud.dialogflow_v2.types.OutputAudioConfig): + Instructs the speech synthesizer how to + generate the output audio. If this field is not + set and agent-level speech synthesizer is not + configured, no output audio is generated. + output_audio_config_mask (google.protobuf.field_mask_pb2.FieldMask): + Mask for + [output_audio_config][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.output_audio_config] + indicating which settings in this request-level config + should override speech synthesizer settings defined at + agent-level. + + If unspecified or empty, + [output_audio_config][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.output_audio_config] + replaces the agent-level config in its entirety. + input_audio (bytes): + The input audio content to be recognized. Must be sent if + ``query_input`` was set to a streaming input audio config. + The complete audio over all streaming messages must not + exceed 1 minute. + """ + + session = proto.Field( + proto.STRING, + number=1, + ) + query_params = proto.Field( + proto.MESSAGE, + number=2, + message='QueryParameters', + ) + query_input = proto.Field( + proto.MESSAGE, + number=3, + message='QueryInput', + ) + single_utterance = proto.Field( + proto.BOOL, + number=4, + ) + output_audio_config = proto.Field( + proto.MESSAGE, + number=5, + message=gcd_audio_config.OutputAudioConfig, + ) + output_audio_config_mask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + input_audio = proto.Field( + proto.BYTES, + number=6, + ) + + +class StreamingDetectIntentResponse(proto.Message): + r"""The top-level message returned from the ``StreamingDetectIntent`` + method. + + Multiple response messages can be returned in order: + + 1. If the ``StreamingDetectIntentRequest.input_audio`` field was + set, the ``recognition_result`` field is populated for one or + more messages. See the + [StreamingRecognitionResult][google.cloud.dialogflow.v2.StreamingRecognitionResult] + message for details about the result message sequence. + + 2. The next message contains ``response_id``, ``query_result`` and + optionally ``webhook_status`` if a WebHook was called. + + Attributes: + response_id (str): + The unique identifier of the response. It can + be used to locate a response in the training + example set or for reporting issues. + recognition_result (google.cloud.dialogflow_v2.types.StreamingRecognitionResult): + The result of speech recognition. + query_result (google.cloud.dialogflow_v2.types.QueryResult): + The result of the conversational query or + event processing. + webhook_status (google.rpc.status_pb2.Status): + Specifies the status of the webhook request. + output_audio (bytes): + The audio data bytes encoded as specified in the request. + Note: The output audio is generated based on the values of + default platform text responses found in the + ``query_result.fulfillment_messages`` field. If multiple + default text responses exist, they will be concatenated when + generating audio. If no default platform text responses + exist, the generated audio content will be empty. + + In some scenarios, multiple output audio fields may be + present in the response structure. In these cases, only the + top-most-level audio output has content. + output_audio_config (google.cloud.dialogflow_v2.types.OutputAudioConfig): + The config used by the speech synthesizer to + generate the output audio. + """ + + response_id = proto.Field( + proto.STRING, + number=1, + ) + recognition_result = proto.Field( + proto.MESSAGE, + number=2, + message='StreamingRecognitionResult', + ) + query_result = proto.Field( + proto.MESSAGE, + number=3, + message='QueryResult', + ) + webhook_status = proto.Field( + proto.MESSAGE, + number=4, + message=status_pb2.Status, + ) + output_audio = proto.Field( + proto.BYTES, + number=5, + ) + output_audio_config = proto.Field( + proto.MESSAGE, + number=6, + message=gcd_audio_config.OutputAudioConfig, + ) + + +class StreamingRecognitionResult(proto.Message): + r"""Contains a speech recognition result corresponding to a portion of + the audio that is currently being processed or an indication that + this is the end of the single requested utterance. + + While end-user audio is being processed, Dialogflow sends a series + of results. Each result may contain a ``transcript`` value. A + transcript represents a portion of the utterance. While the + recognizer is processing audio, transcript values may be interim + values or finalized values. Once a transcript is finalized, the + ``is_final`` value is set to true and processing continues for the + next transcript. + + If + ``StreamingDetectIntentRequest.query_input.audio_config.single_utterance`` + was true, and the recognizer has completed processing audio, the + ``message_type`` value is set to \`END_OF_SINGLE_UTTERANCE and the + following (last) result contains the last finalized transcript. + + The complete end-user utterance is determined by concatenating the + finalized transcript values received for the series of results. + + In the following example, single utterance is enabled. In the case + where single utterance is not enabled, result 7 would not occur. + + :: + + Num | transcript | message_type | is_final + --- | ----------------------- | ----------------------- | -------- + 1 | "tube" | TRANSCRIPT | false + 2 | "to be a" | TRANSCRIPT | false + 3 | "to be" | TRANSCRIPT | false + 4 | "to be or not to be" | TRANSCRIPT | true + 5 | "that's" | TRANSCRIPT | false + 6 | "that is | TRANSCRIPT | false + 7 | unset | END_OF_SINGLE_UTTERANCE | unset + 8 | " that is the question" | TRANSCRIPT | true + + Concatenating the finalized transcripts with ``is_final`` set to + true, the complete utterance becomes "to be or not to be that is the + question". + + Attributes: + message_type (google.cloud.dialogflow_v2.types.StreamingRecognitionResult.MessageType): + Type of the result message. + transcript (str): + Transcript text representing the words that the user spoke. + Populated if and only if ``message_type`` = ``TRANSCRIPT``. + is_final (bool): + If ``false``, the ``StreamingRecognitionResult`` represents + an interim result that may change. If ``true``, the + recognizer will not return any further hypotheses about this + piece of the audio. May only be populated for + ``message_type`` = ``TRANSCRIPT``. + confidence (float): + The Speech confidence between 0.0 and 1.0 for the current + portion of audio. A higher number indicates an estimated + greater likelihood that the recognized words are correct. + The default of 0.0 is a sentinel value indicating that + confidence was not set. + + This field is typically only provided if ``is_final`` is + true and you should not rely on it being accurate or even + set. + speech_word_info (Sequence[google.cloud.dialogflow_v2.types.SpeechWordInfo]): + Word-specific information for the words recognized by Speech + in + [transcript][google.cloud.dialogflow.v2.StreamingRecognitionResult.transcript]. + Populated if and only if ``message_type`` = ``TRANSCRIPT`` + and [InputAudioConfig.enable_word_info] is set. + speech_end_offset (google.protobuf.duration_pb2.Duration): + Time offset of the end of this Speech recognition result + relative to the beginning of the audio. Only populated for + ``message_type`` = ``TRANSCRIPT``. + language_code (str): + Detected language code for the transcript. + """ + class MessageType(proto.Enum): + r"""Type of the response message.""" + MESSAGE_TYPE_UNSPECIFIED = 0 + TRANSCRIPT = 1 + END_OF_SINGLE_UTTERANCE = 2 + + message_type = proto.Field( + proto.ENUM, + number=1, + enum=MessageType, + ) + transcript = proto.Field( + proto.STRING, + number=2, + ) + is_final = proto.Field( + proto.BOOL, + number=3, + ) + confidence = proto.Field( + proto.FLOAT, + number=4, + ) + speech_word_info = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=gcd_audio_config.SpeechWordInfo, + ) + speech_end_offset = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) + language_code = proto.Field( + proto.STRING, + number=10, + ) + + +class TextInput(proto.Message): + r"""Represents the natural language text to be processed. + + Attributes: + text (str): + Required. The UTF-8 encoded natural language + text to be processed. Text length must not + exceed 256 characters. + language_code (str): + Required. The language of this conversational query. See + `Language + Support `__ + for a list of the currently supported language codes. Note + that queries in the same session do not necessarily need to + specify the same language. + """ + + text = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class EventInput(proto.Message): + r"""Events allow for matching intents by event name instead of the + natural language input. For instance, input + ```` + can trigger a personalized welcome response. The parameter ``name`` + may be used by the agent in the response: + ``"Hello #welcome_event.name! What can I do for you today?"``. + + Attributes: + name (str): + Required. The unique identifier of the event. + parameters (google.protobuf.struct_pb2.Struct): + The collection of parameters associated with + the event. + Depending on your protocol or client library + language, this is a map, associative array, + symbol table, dictionary, or JSON object + composed of a collection of (MapKey, MapValue) + pairs: + - MapKey type: string + - MapKey value: parameter name + - MapValue type: + - If parameter's entity type is a + composite entity: map - Else: depending on + parameter value type, could be one of string, + number, boolean, null, list or map + - MapValue value: + - If parameter's entity type is a + composite entity: map from composite + entity property names to property values - + Else: parameter value + language_code (str): + Required. The language of this query. See `Language + Support `__ + for a list of the currently supported language codes. Note + that queries in the same session do not necessarily need to + specify the same language. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + parameters = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class SentimentAnalysisRequestConfig(proto.Message): + r"""Configures the types of sentiment analysis to perform. + + Attributes: + analyze_query_text_sentiment (bool): + Instructs the service to perform sentiment analysis on + ``query_text``. If not provided, sentiment analysis is not + performed on ``query_text``. + """ + + analyze_query_text_sentiment = proto.Field( + proto.BOOL, + number=1, + ) + + +class SentimentAnalysisResult(proto.Message): + r"""The result of sentiment analysis. Sentiment analysis inspects user + input and identifies the prevailing subjective opinion, especially + to determine a user's attitude as positive, negative, or neutral. + For [Participants.DetectIntent][], it needs to be configured in + [DetectIntentRequest.query_params][google.cloud.dialogflow.v2.DetectIntentRequest.query_params]. + For [Participants.StreamingDetectIntent][], it needs to be + configured in + [StreamingDetectIntentRequest.query_params][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_params]. + And for + [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent] + and + [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent], + it needs to be configured in + [ConversationProfile.human_agent_assistant_config][google.cloud.dialogflow.v2.ConversationProfile.human_agent_assistant_config] + + Attributes: + query_text_sentiment (google.cloud.dialogflow_v2.types.Sentiment): + The sentiment analysis result for ``query_text``. + """ + + query_text_sentiment = proto.Field( + proto.MESSAGE, + number=1, + message='Sentiment', + ) + + +class Sentiment(proto.Message): + r"""The sentiment, such as positive/negative feeling or + association, for a unit of analysis, such as the query text. + + Attributes: + score (float): + Sentiment score between -1.0 (negative + sentiment) and 1.0 (positive sentiment). + magnitude (float): + A non-negative number in the [0, +inf) range, which + represents the absolute magnitude of sentiment, regardless + of score (positive or negative). + """ + + score = proto.Field( + proto.FLOAT, + number=1, + ) + magnitude = proto.Field( + proto.FLOAT, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/session_entity_type.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/session_entity_type.py new file mode 100644 index 000000000..6924dfd26 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/session_entity_type.py @@ -0,0 +1,251 @@ +# -*- 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.dialogflow_v2.types import entity_type +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + 'SessionEntityType', + 'ListSessionEntityTypesRequest', + 'ListSessionEntityTypesResponse', + 'GetSessionEntityTypeRequest', + 'CreateSessionEntityTypeRequest', + 'UpdateSessionEntityTypeRequest', + 'DeleteSessionEntityTypeRequest', + }, +) + + +class SessionEntityType(proto.Message): + r"""A session represents a conversation between a Dialogflow agent and + an end-user. You can create special entities, called session + entities, during a session. Session entities can extend or replace + custom entity types and only exist during the session that they were + created for. All session data, including session entities, is stored + by Dialogflow for 20 minutes. + + For more information, see the `session entity + guide `__. + + Attributes: + name (str): + Required. The unique identifier of this session entity type. + Format: + ``projects//agent/sessions//entityTypes/``, + or + ``projects//agent/environments//users//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. If ``User ID`` is not specified, we + assume default '-' user. + + ```` must be the display name of + an existing entity type in the same agent that will be + overridden or supplemented. + entity_override_mode (google.cloud.dialogflow_v2.types.SessionEntityType.EntityOverrideMode): + Required. Indicates whether the additional + data should override or supplement the custom + entity type definition. + entities (Sequence[google.cloud.dialogflow_v2.types.EntityType.Entity]): + Required. The collection of entities + associated with this session entity type. + """ + class EntityOverrideMode(proto.Enum): + r"""The types of modifications for a session entity type.""" + ENTITY_OVERRIDE_MODE_UNSPECIFIED = 0 + ENTITY_OVERRIDE_MODE_OVERRIDE = 1 + ENTITY_OVERRIDE_MODE_SUPPLEMENT = 2 + + name = proto.Field( + proto.STRING, + number=1, + ) + entity_override_mode = proto.Field( + proto.ENUM, + number=2, + enum=EntityOverrideMode, + ) + entities = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=entity_type.EntityType.Entity, + ) + + +class ListSessionEntityTypesRequest(proto.Message): + r"""The request message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2.SessionEntityTypes.ListSessionEntityTypes]. + + Attributes: + parent (str): + Required. The session to list all session entity types from. + Format: + ``projects//agent/sessions/`` or + ``projects//agent/environments//users// sessions/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. If ``User ID`` is not specified, we + assume default '-' user. + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListSessionEntityTypesResponse(proto.Message): + r"""The response message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2.SessionEntityTypes.ListSessionEntityTypes]. + + Attributes: + session_entity_types (Sequence[google.cloud.dialogflow_v2.types.SessionEntityType]): + The list of session entity types. There will be a maximum + number of items returned based on the page_size field in the + request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + session_entity_types = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SessionEntityType', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetSessionEntityTypeRequest(proto.Message): + r"""The request message for + [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.GetSessionEntityType]. + + Attributes: + name (str): + Required. The name of the session entity type. Format: + ``projects//agent/sessions//entityTypes/`` + or + ``projects//agent/environments//users//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. If ``User ID`` is not specified, we + assume default '-' user. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateSessionEntityTypeRequest(proto.Message): + r"""The request message for + [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.CreateSessionEntityType]. + + Attributes: + parent (str): + Required. The session to create a session entity type for. + Format: + ``projects//agent/sessions/`` or + ``projects//agent/environments//users// sessions/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. If ``User ID`` is not specified, we + assume default '-' user. + session_entity_type (google.cloud.dialogflow_v2.types.SessionEntityType): + Required. The session entity type to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + session_entity_type = proto.Field( + proto.MESSAGE, + number=2, + message='SessionEntityType', + ) + + +class UpdateSessionEntityTypeRequest(proto.Message): + r"""The request message for + [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.UpdateSessionEntityType]. + + Attributes: + session_entity_type (google.cloud.dialogflow_v2.types.SessionEntityType): + Required. The session entity type to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which fields + get updated. + """ + + session_entity_type = proto.Field( + proto.MESSAGE, + number=1, + message='SessionEntityType', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteSessionEntityTypeRequest(proto.Message): + r"""The request message for + [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.DeleteSessionEntityType]. + + Attributes: + name (str): + Required. The name of the entity type to delete. Format: + ``projects//agent/sessions//entityTypes/`` + or + ``projects//agent/environments//users//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. If ``User ID`` is not specified, we + assume default '-' user. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/validation_result.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/validation_result.py new file mode 100644 index 000000000..c29169380 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/validation_result.py @@ -0,0 +1,95 @@ +# -*- 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.dialogflow.v2', + manifest={ + 'ValidationError', + 'ValidationResult', + }, +) + + +class ValidationError(proto.Message): + r"""Represents a single validation error. + + Attributes: + severity (google.cloud.dialogflow_v2.types.ValidationError.Severity): + The severity of the error. + entries (Sequence[str]): + The names of the entries that the error is + associated with. Format: + + - "projects//agent", if the error is + associated with the entire agent. + - "projects//agent/intents/", if the error is associated with certain + intents. + - "projects//agent/intents//trainingPhrases/", if + the error is associated with certain intent + training phrases. - "projects//agent/intents//parameters/", if the error is + associated with certain intent parameters. - + "projects//agent/entities/", if the error is associated with certain + entities. + error_message (str): + The detailed error message. + """ + class Severity(proto.Enum): + r"""Represents a level of severity.""" + SEVERITY_UNSPECIFIED = 0 + INFO = 1 + WARNING = 2 + ERROR = 3 + CRITICAL = 4 + + severity = proto.Field( + proto.ENUM, + number=1, + enum=Severity, + ) + entries = proto.RepeatedField( + proto.STRING, + number=3, + ) + error_message = proto.Field( + proto.STRING, + number=4, + ) + + +class ValidationResult(proto.Message): + r"""Represents the output of agent validation. + + Attributes: + validation_errors (Sequence[google.cloud.dialogflow_v2.types.ValidationError]): + Contains all validation errors. + """ + + validation_errors = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ValidationError', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/version.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/version.py new file mode 100644 index 000000000..aad1a9afa --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/version.py @@ -0,0 +1,265 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + 'Version', + 'ListVersionsRequest', + 'ListVersionsResponse', + 'GetVersionRequest', + 'CreateVersionRequest', + 'UpdateVersionRequest', + 'DeleteVersionRequest', + }, +) + + +class Version(proto.Message): + r"""You can create multiple versions of your agent and publish them to + separate environments. + + When you edit an agent, you are editing the draft agent. At any + point, you can save the draft agent as an agent version, which is an + immutable snapshot of your agent. + + When you save the draft agent, it is published to the default + environment. When you create agent versions, you can publish them to + custom environments. You can create a variety of custom environments + for: + + - testing + - development + - production + - etc. + + For more information, see the `versions and environments + guide `__. + + Attributes: + name (str): + Output only. The unique identifier of this agent version. + Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + description (str): + Optional. The developer-provided description + of this version. + version_number (int): + Output only. The sequential number of this + version. This field is read-only which means it + cannot be set by create and update methods. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation time of this + version. This field is read-only, i.e., it + cannot be set by create and update methods. + status (google.cloud.dialogflow_v2.types.Version.VersionStatus): + Output only. The status of this version. This + field is read-only and cannot be set by create + and update methods. + """ + class VersionStatus(proto.Enum): + r"""The status of a version.""" + VERSION_STATUS_UNSPECIFIED = 0 + IN_PROGRESS = 1 + READY = 2 + FAILED = 3 + + name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + version_number = proto.Field( + proto.INT32, + number=3, + ) + create_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + status = proto.Field( + proto.ENUM, + number=6, + enum=VersionStatus, + ) + + +class ListVersionsRequest(proto.Message): + r"""The request message for + [Versions.ListVersions][google.cloud.dialogflow.v2.Versions.ListVersions]. + + Attributes: + parent (str): + Required. The agent to list all versions from. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListVersionsResponse(proto.Message): + r"""The response message for + [Versions.ListVersions][google.cloud.dialogflow.v2.Versions.ListVersions]. + + Attributes: + versions (Sequence[google.cloud.dialogflow_v2.types.Version]): + The list of agent versions. There will be a maximum number + of items returned based on the page_size field in the + request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + versions = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Version', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetVersionRequest(proto.Message): + r"""The request message for + [Versions.GetVersion][google.cloud.dialogflow.v2.Versions.GetVersion]. + + Attributes: + name (str): + Required. The name of the version. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateVersionRequest(proto.Message): + r"""The request message for + [Versions.CreateVersion][google.cloud.dialogflow.v2.Versions.CreateVersion]. + + Attributes: + parent (str): + Required. The agent to create a version for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + version (google.cloud.dialogflow_v2.types.Version): + Required. The version to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + version = proto.Field( + proto.MESSAGE, + number=2, + message='Version', + ) + + +class UpdateVersionRequest(proto.Message): + r"""The request message for + [Versions.UpdateVersion][google.cloud.dialogflow.v2.Versions.UpdateVersion]. + + Attributes: + version (google.cloud.dialogflow_v2.types.Version): + Required. The version to update. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. + """ + + version = proto.Field( + proto.MESSAGE, + number=1, + message='Version', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteVersionRequest(proto.Message): + r"""The request message for + [Versions.DeleteVersion][google.cloud.dialogflow.v2.Versions.DeleteVersion]. + + Attributes: + name (str): + Required. The name of the version to delete. Supported + formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/webhook.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/webhook.py new file mode 100644 index 000000000..3c1887f7c --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/webhook.py @@ -0,0 +1,231 @@ +# -*- 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.dialogflow_v2.types import context +from google.cloud.dialogflow_v2.types import intent +from google.cloud.dialogflow_v2.types import session as gcd_session +from google.cloud.dialogflow_v2.types import session_entity_type +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2', + manifest={ + 'WebhookRequest', + 'WebhookResponse', + 'OriginalDetectIntentRequest', + }, +) + + +class WebhookRequest(proto.Message): + r"""The request message for a webhook call. + + Attributes: + session (str): + The unique identifier of detectIntent request session. Can + be used to identify end-user inside webhook implementation. + Format: + ``projects//agent/sessions/``, or + ``projects//agent/environments//users//sessions/``. + response_id (str): + The unique identifier of the response. Contains the same + value as ``[Streaming]DetectIntentResponse.response_id``. + query_result (google.cloud.dialogflow_v2.types.QueryResult): + The result of the conversational query or event processing. + Contains the same value as + ``[Streaming]DetectIntentResponse.query_result``. + original_detect_intent_request (google.cloud.dialogflow_v2.types.OriginalDetectIntentRequest): + Optional. The contents of the original request that was + passed to ``[Streaming]DetectIntent`` call. + """ + + session = proto.Field( + proto.STRING, + number=4, + ) + response_id = proto.Field( + proto.STRING, + number=1, + ) + query_result = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_session.QueryResult, + ) + original_detect_intent_request = proto.Field( + proto.MESSAGE, + number=3, + message='OriginalDetectIntentRequest', + ) + + +class WebhookResponse(proto.Message): + r"""The response message for a webhook call. + + This response is validated by the Dialogflow server. If validation + fails, an error will be returned in the + [QueryResult.diagnostic_info][google.cloud.dialogflow.v2.QueryResult.diagnostic_info] + field. Setting JSON fields to an empty value with the wrong type is + a common error. To avoid this error: + + - Use ``""`` for empty strings + - Use ``{}`` or ``null`` for empty objects + - Use ``[]`` or ``null`` for empty arrays + + For more information, see the `Protocol Buffers Language + Guide `__. + + Attributes: + fulfillment_text (str): + Optional. The text response message intended for the + end-user. It is recommended to use + ``fulfillment_messages.text.text[0]`` instead. When + provided, Dialogflow uses this field to populate + [QueryResult.fulfillment_text][google.cloud.dialogflow.v2.QueryResult.fulfillment_text] + sent to the integration or API caller. + fulfillment_messages (Sequence[google.cloud.dialogflow_v2.types.Intent.Message]): + Optional. The rich response messages intended for the + end-user. When provided, Dialogflow uses this field to + populate + [QueryResult.fulfillment_messages][google.cloud.dialogflow.v2.QueryResult.fulfillment_messages] + sent to the integration or API caller. + source (str): + Optional. A custom field used to identify the webhook + source. Arbitrary strings are supported. When provided, + Dialogflow uses this field to populate + [QueryResult.webhook_source][google.cloud.dialogflow.v2.QueryResult.webhook_source] + sent to the integration or API caller. + payload (google.protobuf.struct_pb2.Struct): + Optional. This field can be used to pass custom data from + your webhook to the integration or API caller. Arbitrary + JSON objects are supported. When provided, Dialogflow uses + this field to populate + [QueryResult.webhook_payload][google.cloud.dialogflow.v2.QueryResult.webhook_payload] + sent to the integration or API caller. This field is also + used by the `Google Assistant + integration `__ + for rich response messages. See the format definition at + `Google Assistant Dialogflow webhook + format `__ + output_contexts (Sequence[google.cloud.dialogflow_v2.types.Context]): + Optional. The collection of output contexts that will + overwrite currently active contexts for the session and + reset their lifespans. When provided, Dialogflow uses this + field to populate + [QueryResult.output_contexts][google.cloud.dialogflow.v2.QueryResult.output_contexts] + sent to the integration or API caller. + followup_event_input (google.cloud.dialogflow_v2.types.EventInput): + Optional. Invokes the supplied events. When this field is + set, Dialogflow ignores the ``fulfillment_text``, + ``fulfillment_messages``, and ``payload`` fields. + session_entity_types (Sequence[google.cloud.dialogflow_v2.types.SessionEntityType]): + Optional. Additional session entity types to replace or + extend developer entity types with. The entity synonyms + apply to all languages and persist for the session. Setting + this data from a webhook overwrites the session entity types + that have been set using ``detectIntent``, + ``streamingDetectIntent`` or + [SessionEntityType][google.cloud.dialogflow.v2.SessionEntityType] + management methods. + """ + + fulfillment_text = proto.Field( + proto.STRING, + number=1, + ) + fulfillment_messages = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=intent.Intent.Message, + ) + source = proto.Field( + proto.STRING, + number=3, + ) + payload = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Struct, + ) + output_contexts = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=context.Context, + ) + followup_event_input = proto.Field( + proto.MESSAGE, + number=6, + message=gcd_session.EventInput, + ) + session_entity_types = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=session_entity_type.SessionEntityType, + ) + + +class OriginalDetectIntentRequest(proto.Message): + r"""Represents the contents of the original request that was passed to + the ``[Streaming]DetectIntent`` call. + + Attributes: + source (str): + The source of this request, e.g., ``google``, ``facebook``, + ``slack``. It is set by Dialogflow-owned servers. + version (str): + Optional. The version of the protocol used + for this request. This field is AoG-specific. + payload (google.protobuf.struct_pb2.Struct): + Optional. This field is set to the value of the + ``QueryParameters.payload`` field passed in the request. + Some integrations that query a Dialogflow agent may provide + additional information in the payload. + + In particular, for the Dialogflow Phone Gateway integration, + this field has the form: + + .. raw:: html + +
{
+                 "telephony": {
+                   "caller_id": "+18558363987"
+                 }
+                }
+ + Note: The caller ID field (``caller_id``) will be redacted + for Trial Edition agents and populated with the caller ID in + `E.164 format `__ for + Essentials Edition agents. + """ + + source = proto.Field( + proto.STRING, + number=1, + ) + version = proto.Field( + proto.STRING, + number=2, + ) + payload = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/mypy.ini b/owl-bot-staging/v2/mypy.ini new file mode 100644 index 000000000..4505b4854 --- /dev/null +++ b/owl-bot-staging/v2/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v2/noxfile.py b/owl-bot-staging/v2/noxfile.py new file mode 100644 index 000000000..7d0aa4f8b --- /dev/null +++ b/owl-bot-staging/v2/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', '3.10']) +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/dialogflow_v2/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.9') +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', '3.8', '3.9']) +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.9') +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/v2/scripts/fixup_dialogflow_v2_keywords.py b/owl-bot-staging/v2/scripts/fixup_dialogflow_v2_keywords.py new file mode 100644 index 000000000..d3931a43b --- /dev/null +++ b/owl-bot-staging/v2/scripts/fixup_dialogflow_v2_keywords.py @@ -0,0 +1,258 @@ +#! /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 dialogflowCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'analyze_content': ('participant', 'text_input', 'event_input', 'reply_audio_config', 'query_params', 'assist_query_params', 'request_id', ), + 'batch_create_entities': ('parent', 'entities', 'language_code', ), + 'batch_delete_entities': ('parent', 'entity_values', 'language_code', ), + 'batch_delete_entity_types': ('parent', 'entity_type_names', ), + 'batch_delete_intents': ('parent', 'intents', ), + 'batch_update_entities': ('parent', 'entities', 'language_code', 'update_mask', ), + 'batch_update_entity_types': ('parent', 'entity_type_batch_uri', 'entity_type_batch_inline', 'language_code', 'update_mask', ), + 'batch_update_intents': ('parent', 'intent_batch_uri', 'intent_batch_inline', 'language_code', 'update_mask', 'intent_view', ), + 'complete_conversation': ('name', ), + 'create_context': ('parent', 'context', ), + 'create_conversation': ('parent', 'conversation', 'conversation_id', ), + 'create_conversation_profile': ('parent', 'conversation_profile', ), + 'create_document': ('parent', 'document', ), + 'create_entity_type': ('parent', 'entity_type', 'language_code', ), + 'create_environment': ('parent', 'environment', 'environment_id', ), + 'create_intent': ('parent', 'intent', 'language_code', 'intent_view', ), + 'create_knowledge_base': ('parent', 'knowledge_base', ), + 'create_participant': ('parent', 'participant', ), + 'create_session_entity_type': ('parent', 'session_entity_type', ), + 'create_version': ('parent', 'version', ), + 'delete_agent': ('parent', ), + 'delete_all_contexts': ('parent', ), + 'delete_context': ('name', ), + 'delete_conversation_profile': ('name', ), + 'delete_document': ('name', ), + 'delete_entity_type': ('name', ), + 'delete_environment': ('name', ), + 'delete_intent': ('name', ), + 'delete_knowledge_base': ('name', 'force', ), + 'delete_session_entity_type': ('name', ), + 'delete_version': ('name', ), + 'detect_intent': ('session', 'query_input', 'query_params', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), + 'export_agent': ('parent', 'agent_uri', ), + 'export_document': ('name', 'gcs_destination', 'export_full_content', 'smart_messaging_partial_update', ), + 'get_agent': ('parent', ), + 'get_context': ('name', ), + 'get_conversation': ('name', ), + 'get_conversation_profile': ('name', ), + 'get_document': ('name', ), + 'get_entity_type': ('name', 'language_code', ), + 'get_environment': ('name', ), + 'get_environment_history': ('parent', 'page_size', 'page_token', ), + 'get_fulfillment': ('name', ), + 'get_intent': ('name', 'language_code', 'intent_view', ), + 'get_knowledge_base': ('name', ), + 'get_participant': ('name', ), + 'get_session_entity_type': ('name', ), + 'get_validation_result': ('parent', 'language_code', ), + 'get_version': ('name', ), + 'import_agent': ('parent', 'agent_uri', 'agent_content', ), + 'list_answer_records': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_contexts': ('parent', 'page_size', 'page_token', ), + 'list_conversation_profiles': ('parent', 'page_size', 'page_token', ), + 'list_conversations': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_documents': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_entity_types': ('parent', 'language_code', 'page_size', 'page_token', ), + 'list_environments': ('parent', 'page_size', 'page_token', ), + 'list_intents': ('parent', 'language_code', 'intent_view', 'page_size', 'page_token', ), + 'list_knowledge_bases': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_messages': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_participants': ('parent', 'page_size', 'page_token', ), + 'list_session_entity_types': ('parent', 'page_size', 'page_token', ), + 'list_versions': ('parent', 'page_size', 'page_token', ), + 'reload_document': ('name', 'content_uri', 'import_gcs_custom_metadata', 'smart_messaging_partial_update', ), + 'restore_agent': ('parent', 'agent_uri', 'agent_content', ), + 'search_agents': ('parent', 'page_size', 'page_token', ), + 'set_agent': ('agent', 'update_mask', ), + 'streaming_detect_intent': ('session', 'query_input', 'query_params', 'single_utterance', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), + 'suggest_articles': ('parent', 'latest_message', 'context_size', 'assist_query_params', ), + 'suggest_faq_answers': ('parent', 'latest_message', 'context_size', 'assist_query_params', ), + 'train_agent': ('parent', ), + 'update_answer_record': ('answer_record', 'update_mask', ), + 'update_context': ('context', 'update_mask', ), + 'update_conversation_profile': ('conversation_profile', 'update_mask', ), + 'update_document': ('document', 'update_mask', ), + 'update_entity_type': ('entity_type', 'language_code', 'update_mask', ), + 'update_environment': ('environment', 'update_mask', 'allow_load_to_draft_and_discard_changes', ), + 'update_fulfillment': ('fulfillment', 'update_mask', ), + 'update_intent': ('intent', 'language_code', 'update_mask', 'intent_view', ), + 'update_knowledge_base': ('knowledge_base', 'update_mask', ), + 'update_participant': ('participant', 'update_mask', ), + 'update_session_entity_type': ('session_entity_type', 'update_mask', ), + 'update_version': ('version', 'update_mask', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=dialogflowCallTransformer(), +): + """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 dialogflow client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v2/setup.py b/owl-bot-staging/v2/setup.py new file mode 100644 index 000000000..5f320d08d --- /dev/null +++ b/owl-bot-staging/v2/setup.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, 'README.rst') +with io.open(readme_filename, encoding='utf-8') as readme_file: + readme = readme_file.read() + +setuptools.setup( + name='google-cloud-dialogflow', + 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.28.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.19.7', + ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v2/tests/__init__.py b/owl-bot-staging/v2/tests/__init__.py new file mode 100644 index 000000000..b54a5fcc4 --- /dev/null +++ b/owl-bot-staging/v2/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/v2/tests/unit/__init__.py b/owl-bot-staging/v2/tests/unit/__init__.py new file mode 100644 index 000000000..b54a5fcc4 --- /dev/null +++ b/owl-bot-staging/v2/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/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/__init__.py new file mode 100644 index 000000000..b54a5fcc4 --- /dev/null +++ b/owl-bot-staging/v2/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/v2/tests/unit/gapic/dialogflow_v2/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/__init__.py new file mode 100644 index 000000000..b54a5fcc4 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/__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/v2/tests/unit/gapic/dialogflow_v2/test_agents.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_agents.py new file mode 100644 index 000000000..c7524ef17 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_agents.py @@ -0,0 +1,3084 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.agents import AgentsAsyncClient +from google.cloud.dialogflow_v2.services.agents import AgentsClient +from google.cloud.dialogflow_v2.services.agents import pagers +from google.cloud.dialogflow_v2.services.agents import transports +from google.cloud.dialogflow_v2.types import agent +from google.cloud.dialogflow_v2.types import agent as gcd_agent +from google.cloud.dialogflow_v2.types import validation_result +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 struct_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert AgentsClient._get_default_mtls_endpoint(None) is None + assert AgentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AgentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AgentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AgentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AgentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + AgentsClient, + AgentsAsyncClient, +]) +def test_agents_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AgentsGrpcTransport, "grpc"), + (transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_agents_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + AgentsClient, + AgentsAsyncClient, +]) +def test_agents_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 == 'dialogflow.googleapis.com:443' + + +def test_agents_client_get_transport_class(): + transport = AgentsClient.get_transport_class() + available_transports = [ + transports.AgentsGrpcTransport, + ] + assert transport in available_transports + + transport = AgentsClient.get_transport_class("grpc") + assert transport == transports.AgentsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AgentsClient, transports.AgentsGrpcTransport, "grpc"), + (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(AgentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AgentsClient)) +@mock.patch.object(AgentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AgentsAsyncClient)) +def test_agents_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(AgentsClient, '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(AgentsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (AgentsClient, transports.AgentsGrpcTransport, "grpc", "true"), + (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AgentsClient, transports.AgentsGrpcTransport, "grpc", "false"), + (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(AgentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AgentsClient)) +@mock.patch.object(AgentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AgentsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_agents_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AgentsClient, transports.AgentsGrpcTransport, "grpc"), + (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_agents_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AgentsClient, transports.AgentsGrpcTransport, "grpc"), + (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_agents_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_agents_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2.services.agents.transports.AgentsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AgentsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_get_agent(transport: str = 'grpc', request_type=agent.GetAgentRequest): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = agent.Agent( + parent='parent_value', + display_name='display_name_value', + default_language_code='default_language_code_value', + supported_language_codes=['supported_language_codes_value'], + time_zone='time_zone_value', + description='description_value', + avatar_uri='avatar_uri_value', + enable_logging=True, + match_mode=agent.Agent.MatchMode.MATCH_MODE_HYBRID, + classification_threshold=0.25520000000000004, + api_version=agent.Agent.ApiVersion.API_VERSION_V1, + tier=agent.Agent.Tier.TIER_STANDARD, + ) + response = client.get_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, agent.Agent) + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.default_language_code == 'default_language_code_value' + assert response.supported_language_codes == ['supported_language_codes_value'] + assert response.time_zone == 'time_zone_value' + assert response.description == 'description_value' + assert response.avatar_uri == 'avatar_uri_value' + assert response.enable_logging is True + assert response.match_mode == agent.Agent.MatchMode.MATCH_MODE_HYBRID + assert math.isclose(response.classification_threshold, 0.25520000000000004, rel_tol=1e-6) + assert response.api_version == agent.Agent.ApiVersion.API_VERSION_V1 + assert response.tier == agent.Agent.Tier.TIER_STANDARD + + +def test_get_agent_from_dict(): + test_get_agent(request_type=dict) + + +def test_get_agent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=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_agent), + '__call__') as call: + client.get_agent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetAgentRequest() + + +@pytest.mark.asyncio +async def test_get_agent_async(transport: str = 'grpc_asyncio', request_type=agent.GetAgentRequest): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(agent.Agent( + parent='parent_value', + display_name='display_name_value', + default_language_code='default_language_code_value', + supported_language_codes=['supported_language_codes_value'], + time_zone='time_zone_value', + description='description_value', + avatar_uri='avatar_uri_value', + enable_logging=True, + match_mode=agent.Agent.MatchMode.MATCH_MODE_HYBRID, + classification_threshold=0.25520000000000004, + api_version=agent.Agent.ApiVersion.API_VERSION_V1, + tier=agent.Agent.Tier.TIER_STANDARD, + )) + response = await client.get_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, agent.Agent) + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.default_language_code == 'default_language_code_value' + assert response.supported_language_codes == ['supported_language_codes_value'] + assert response.time_zone == 'time_zone_value' + assert response.description == 'description_value' + assert response.avatar_uri == 'avatar_uri_value' + assert response.enable_logging is True + assert response.match_mode == agent.Agent.MatchMode.MATCH_MODE_HYBRID + assert math.isclose(response.classification_threshold, 0.25520000000000004, rel_tol=1e-6) + assert response.api_version == agent.Agent.ApiVersion.API_VERSION_V1 + assert response.tier == agent.Agent.Tier.TIER_STANDARD + + +@pytest.mark.asyncio +async def test_get_agent_async_from_dict(): + await test_get_agent_async(request_type=dict) + + +def test_get_agent_field_headers(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.GetAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_agent), + '__call__') as call: + call.return_value = agent.Agent() + client.get_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_get_agent_field_headers_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.GetAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_agent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.Agent()) + await client.get_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_get_agent_flattened(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = agent.Agent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_agent( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_get_agent_flattened_error(): + client = AgentsClient( + credentials=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_agent( + agent.GetAgentRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_get_agent_flattened_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = agent.Agent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.Agent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_agent( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_agent_flattened_error_async(): + client = AgentsAsyncClient( + credentials=ga_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_agent( + agent.GetAgentRequest(), + parent='parent_value', + ) + + +def test_set_agent(transport: str = 'grpc', request_type=gcd_agent.SetAgentRequest): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_agent.Agent( + parent='parent_value', + display_name='display_name_value', + default_language_code='default_language_code_value', + supported_language_codes=['supported_language_codes_value'], + time_zone='time_zone_value', + description='description_value', + avatar_uri='avatar_uri_value', + enable_logging=True, + match_mode=gcd_agent.Agent.MatchMode.MATCH_MODE_HYBRID, + classification_threshold=0.25520000000000004, + api_version=gcd_agent.Agent.ApiVersion.API_VERSION_V1, + tier=gcd_agent.Agent.Tier.TIER_STANDARD, + ) + response = client.set_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_agent.SetAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_agent.Agent) + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.default_language_code == 'default_language_code_value' + assert response.supported_language_codes == ['supported_language_codes_value'] + assert response.time_zone == 'time_zone_value' + assert response.description == 'description_value' + assert response.avatar_uri == 'avatar_uri_value' + assert response.enable_logging is True + assert response.match_mode == gcd_agent.Agent.MatchMode.MATCH_MODE_HYBRID + assert math.isclose(response.classification_threshold, 0.25520000000000004, rel_tol=1e-6) + assert response.api_version == gcd_agent.Agent.ApiVersion.API_VERSION_V1 + assert response.tier == gcd_agent.Agent.Tier.TIER_STANDARD + + +def test_set_agent_from_dict(): + test_set_agent(request_type=dict) + + +def test_set_agent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent), + '__call__') as call: + client.set_agent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_agent.SetAgentRequest() + + +@pytest.mark.asyncio +async def test_set_agent_async(transport: str = 'grpc_asyncio', request_type=gcd_agent.SetAgentRequest): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_agent.Agent( + parent='parent_value', + display_name='display_name_value', + default_language_code='default_language_code_value', + supported_language_codes=['supported_language_codes_value'], + time_zone='time_zone_value', + description='description_value', + avatar_uri='avatar_uri_value', + enable_logging=True, + match_mode=gcd_agent.Agent.MatchMode.MATCH_MODE_HYBRID, + classification_threshold=0.25520000000000004, + api_version=gcd_agent.Agent.ApiVersion.API_VERSION_V1, + tier=gcd_agent.Agent.Tier.TIER_STANDARD, + )) + response = await client.set_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_agent.SetAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_agent.Agent) + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.default_language_code == 'default_language_code_value' + assert response.supported_language_codes == ['supported_language_codes_value'] + assert response.time_zone == 'time_zone_value' + assert response.description == 'description_value' + assert response.avatar_uri == 'avatar_uri_value' + assert response.enable_logging is True + assert response.match_mode == gcd_agent.Agent.MatchMode.MATCH_MODE_HYBRID + assert math.isclose(response.classification_threshold, 0.25520000000000004, rel_tol=1e-6) + assert response.api_version == gcd_agent.Agent.ApiVersion.API_VERSION_V1 + assert response.tier == gcd_agent.Agent.Tier.TIER_STANDARD + + +@pytest.mark.asyncio +async def test_set_agent_async_from_dict(): + await test_set_agent_async(request_type=dict) + + +def test_set_agent_field_headers(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_agent.SetAgentRequest() + + request.agent.parent = 'agent.parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent), + '__call__') as call: + call.return_value = gcd_agent.Agent() + client.set_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'agent.parent=agent.parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_agent_field_headers_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_agent.SetAgentRequest() + + request.agent.parent = 'agent.parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_agent.Agent()) + await client.set_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'agent.parent=agent.parent/value', + ) in kw['metadata'] + + +def test_set_agent_flattened(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_agent.Agent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_agent( + agent=gcd_agent.Agent(parent='parent_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].agent + mock_val = gcd_agent.Agent(parent='parent_value') + assert arg == mock_val + + +def test_set_agent_flattened_error(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_agent( + gcd_agent.SetAgentRequest(), + agent=gcd_agent.Agent(parent='parent_value'), + ) + + +@pytest.mark.asyncio +async def test_set_agent_flattened_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_agent.Agent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_agent.Agent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_agent( + agent=gcd_agent.Agent(parent='parent_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].agent + mock_val = gcd_agent.Agent(parent='parent_value') + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_set_agent_flattened_error_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_agent( + gcd_agent.SetAgentRequest(), + agent=gcd_agent.Agent(parent='parent_value'), + ) + + +def test_delete_agent(transport: str = 'grpc', request_type=agent.DeleteAgentRequest): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.DeleteAgentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_agent_from_dict(): + test_delete_agent(request_type=dict) + + +def test_delete_agent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=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_agent), + '__call__') as call: + client.delete_agent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent.DeleteAgentRequest() + + +@pytest.mark.asyncio +async def test_delete_agent_async(transport: str = 'grpc_asyncio', request_type=agent.DeleteAgentRequest): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == agent.DeleteAgentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_agent_async_from_dict(): + await test_delete_agent_async(request_type=dict) + + +def test_delete_agent_field_headers(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.DeleteAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_agent), + '__call__') as call: + call.return_value = None + client.delete_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_delete_agent_field_headers_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.DeleteAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_agent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_delete_agent_flattened(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_agent), + '__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_agent( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_delete_agent_flattened_error(): + client = AgentsClient( + credentials=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_agent( + agent.DeleteAgentRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_delete_agent_flattened_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_agent), + '__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_agent( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_agent_flattened_error_async(): + client = AgentsAsyncClient( + credentials=ga_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_agent( + agent.DeleteAgentRequest(), + parent='parent_value', + ) + + +def test_search_agents(transport: str = 'grpc', request_type=agent.SearchAgentsRequest): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_agents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = agent.SearchAgentsResponse( + next_page_token='next_page_token_value', + ) + response = client.search_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.SearchAgentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAgentsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_search_agents_from_dict(): + test_search_agents(request_type=dict) + + +def test_search_agents_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_agents), + '__call__') as call: + client.search_agents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent.SearchAgentsRequest() + + +@pytest.mark.asyncio +async def test_search_agents_async(transport: str = 'grpc_asyncio', request_type=agent.SearchAgentsRequest): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_agents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(agent.SearchAgentsResponse( + next_page_token='next_page_token_value', + )) + response = await client.search_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == agent.SearchAgentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAgentsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_search_agents_async_from_dict(): + await test_search_agents_async(request_type=dict) + + +def test_search_agents_field_headers(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.SearchAgentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_agents), + '__call__') as call: + call.return_value = agent.SearchAgentsResponse() + client.search_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_search_agents_field_headers_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.SearchAgentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_agents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.SearchAgentsResponse()) + await client.search_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_search_agents_flattened(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_agents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = agent.SearchAgentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.search_agents( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_search_agents_flattened_error(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.search_agents( + agent.SearchAgentsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_search_agents_flattened_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_agents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = agent.SearchAgentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.SearchAgentsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.search_agents( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_search_agents_flattened_error_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.search_agents( + agent.SearchAgentsRequest(), + parent='parent_value', + ) + + +def test_search_agents_pager(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_agents), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + agent.SearchAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + agent.Agent(), + ], + next_page_token='abc', + ), + agent.SearchAgentsResponse( + agents=[], + next_page_token='def', + ), + agent.SearchAgentsResponse( + agents=[ + agent.Agent(), + ], + next_page_token='ghi', + ), + agent.SearchAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.search_agents(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, agent.Agent) + for i in results) + +def test_search_agents_pages(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_agents), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + agent.SearchAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + agent.Agent(), + ], + next_page_token='abc', + ), + agent.SearchAgentsResponse( + agents=[], + next_page_token='def', + ), + agent.SearchAgentsResponse( + agents=[ + agent.Agent(), + ], + next_page_token='ghi', + ), + agent.SearchAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + ], + ), + RuntimeError, + ) + pages = list(client.search_agents(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_search_agents_async_pager(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_agents), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent.SearchAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + agent.Agent(), + ], + next_page_token='abc', + ), + agent.SearchAgentsResponse( + agents=[], + next_page_token='def', + ), + agent.SearchAgentsResponse( + agents=[ + agent.Agent(), + ], + next_page_token='ghi', + ), + agent.SearchAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + ], + ), + RuntimeError, + ) + async_pager = await client.search_agents(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, agent.Agent) + for i in responses) + +@pytest.mark.asyncio +async def test_search_agents_async_pages(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_agents), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent.SearchAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + agent.Agent(), + ], + next_page_token='abc', + ), + agent.SearchAgentsResponse( + agents=[], + next_page_token='def', + ), + agent.SearchAgentsResponse( + agents=[ + agent.Agent(), + ], + next_page_token='ghi', + ), + agent.SearchAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.search_agents(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_train_agent(transport: str = 'grpc', request_type=agent.TrainAgentRequest): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.train_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.TrainAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_train_agent_from_dict(): + test_train_agent(request_type=dict) + + +def test_train_agent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_agent), + '__call__') as call: + client.train_agent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent.TrainAgentRequest() + + +@pytest.mark.asyncio +async def test_train_agent_async(transport: str = 'grpc_asyncio', request_type=agent.TrainAgentRequest): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_agent), + '__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.train_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == agent.TrainAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_train_agent_async_from_dict(): + await test_train_agent_async(request_type=dict) + + +def test_train_agent_field_headers(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.TrainAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_agent), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.train_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_train_agent_field_headers_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.TrainAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_agent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.train_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_train_agent_flattened(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_agent), + '__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.train_agent( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_train_agent_flattened_error(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.train_agent( + agent.TrainAgentRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_train_agent_flattened_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_agent), + '__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.train_agent( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_train_agent_flattened_error_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.train_agent( + agent.TrainAgentRequest(), + parent='parent_value', + ) + + +def test_export_agent(transport: str = 'grpc', request_type=agent.ExportAgentRequest): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.export_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.ExportAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_export_agent_from_dict(): + test_export_agent(request_type=dict) + + +def test_export_agent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_agent), + '__call__') as call: + client.export_agent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent.ExportAgentRequest() + + +@pytest.mark.asyncio +async def test_export_agent_async(transport: str = 'grpc_asyncio', request_type=agent.ExportAgentRequest): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_agent), + '__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.export_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == agent.ExportAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_export_agent_async_from_dict(): + await test_export_agent_async(request_type=dict) + + +def test_export_agent_field_headers(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.ExportAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_agent), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.export_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_export_agent_field_headers_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.ExportAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_agent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.export_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_export_agent_flattened(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_agent), + '__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.export_agent( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_export_agent_flattened_error(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.export_agent( + agent.ExportAgentRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_export_agent_flattened_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_agent), + '__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.export_agent( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_export_agent_flattened_error_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.export_agent( + agent.ExportAgentRequest(), + parent='parent_value', + ) + + +def test_import_agent(transport: str = 'grpc', request_type=agent.ImportAgentRequest): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.ImportAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_agent_from_dict(): + test_import_agent(request_type=dict) + + +def test_import_agent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=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_agent), + '__call__') as call: + client.import_agent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent.ImportAgentRequest() + + +@pytest.mark.asyncio +async def test_import_agent_async(transport: str = 'grpc_asyncio', request_type=agent.ImportAgentRequest): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_agent), + '__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_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == agent.ImportAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_agent_async_from_dict(): + await test_import_agent_async(request_type=dict) + + +def test_import_agent_field_headers(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.ImportAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_agent), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_agent_field_headers_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.ImportAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_agent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_restore_agent(transport: str = 'grpc', request_type=agent.RestoreAgentRequest): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.restore_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.RestoreAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_restore_agent_from_dict(): + test_restore_agent(request_type=dict) + + +def test_restore_agent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_agent), + '__call__') as call: + client.restore_agent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent.RestoreAgentRequest() + + +@pytest.mark.asyncio +async def test_restore_agent_async(transport: str = 'grpc_asyncio', request_type=agent.RestoreAgentRequest): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_agent), + '__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.restore_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == agent.RestoreAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_restore_agent_async_from_dict(): + await test_restore_agent_async(request_type=dict) + + +def test_restore_agent_field_headers(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.RestoreAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_agent), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.restore_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_restore_agent_field_headers_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.RestoreAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_agent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.restore_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_get_validation_result(transport: str = 'grpc', request_type=agent.GetValidationResultRequest): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_validation_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = validation_result.ValidationResult( + ) + response = client.get_validation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetValidationResultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, validation_result.ValidationResult) + + +def test_get_validation_result_from_dict(): + test_get_validation_result(request_type=dict) + + +def test_get_validation_result_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=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_validation_result), + '__call__') as call: + client.get_validation_result() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetValidationResultRequest() + + +@pytest.mark.asyncio +async def test_get_validation_result_async(transport: str = 'grpc_asyncio', request_type=agent.GetValidationResultRequest): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_validation_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(validation_result.ValidationResult( + )) + response = await client.get_validation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetValidationResultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, validation_result.ValidationResult) + + +@pytest.mark.asyncio +async def test_get_validation_result_async_from_dict(): + await test_get_validation_result_async(request_type=dict) + + +def test_get_validation_result_field_headers(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.GetValidationResultRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_validation_result), + '__call__') as call: + call.return_value = validation_result.ValidationResult() + client.get_validation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_get_validation_result_field_headers_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.GetValidationResultRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_validation_result), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(validation_result.ValidationResult()) + await client.get_validation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AgentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AgentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AgentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AgentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AgentsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AgentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AgentsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AgentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AgentsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AgentsGrpcTransport, + transports.AgentsGrpcAsyncIOTransport, +]) +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 = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AgentsGrpcTransport, + ) + +def test_agents_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AgentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_agents_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2.services.agents.transports.AgentsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AgentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_agent', + 'set_agent', + 'delete_agent', + 'search_agents', + 'train_agent', + 'export_agent', + 'import_agent', + 'restore_agent', + 'get_validation_result', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +def test_agents_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.dialogflow_v2.services.agents.transports.AgentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AgentsTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_agents_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.dialogflow_v2.services.agents.transports.AgentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AgentsTransport() + adc.assert_called_once() + + +def test_agents_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) + AgentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AgentsGrpcTransport, + transports.AgentsGrpcAsyncIOTransport, + ], +) +def test_agents_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AgentsGrpcTransport, grpc_helpers), + (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_agents_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport]) +def test_agents_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_agents_host_no_port(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_agents_host_with_port(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_agents_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AgentsGrpcTransport( + 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_agents_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AgentsGrpcAsyncIOTransport( + 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.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport]) +def test_agents_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.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport]) +def test_agents_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_agents_grpc_lro_client(): + client = AgentsClient( + 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_agents_grpc_lro_async_client(): + client = AgentsAsyncClient( + 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_agent_path(): + project = "squid" + expected = "projects/{project}/agent".format(project=project, ) + actual = AgentsClient.agent_path(project) + assert expected == actual + + +def test_parse_agent_path(): + expected = { + "project": "clam", + } + path = AgentsClient.agent_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.parse_agent_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AgentsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = AgentsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = AgentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = AgentsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AgentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = AgentsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = AgentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = AgentsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = AgentsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = AgentsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.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.AgentsTransport, '_prep_wrapped_messages') as prep: + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AgentsTransport, '_prep_wrapped_messages') as prep: + transport_class = AgentsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_answer_records.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_answer_records.py new file mode 100644 index 000000000..3b5e9b0f4 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_answer_records.py @@ -0,0 +1,1588 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.answer_records import AnswerRecordsAsyncClient +from google.cloud.dialogflow_v2.services.answer_records import AnswerRecordsClient +from google.cloud.dialogflow_v2.services.answer_records import pagers +from google.cloud.dialogflow_v2.services.answer_records import transports +from google.cloud.dialogflow_v2.types import answer_record +from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record +from google.cloud.dialogflow_v2.types import participant +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert AnswerRecordsClient._get_default_mtls_endpoint(None) is None + assert AnswerRecordsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AnswerRecordsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AnswerRecordsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AnswerRecordsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AnswerRecordsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + AnswerRecordsClient, + AnswerRecordsAsyncClient, +]) +def test_answer_records_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AnswerRecordsGrpcTransport, "grpc"), + (transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_answer_records_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + AnswerRecordsClient, + AnswerRecordsAsyncClient, +]) +def test_answer_records_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 == 'dialogflow.googleapis.com:443' + + +def test_answer_records_client_get_transport_class(): + transport = AnswerRecordsClient.get_transport_class() + available_transports = [ + transports.AnswerRecordsGrpcTransport, + ] + assert transport in available_transports + + transport = AnswerRecordsClient.get_transport_class("grpc") + assert transport == transports.AnswerRecordsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc"), + (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(AnswerRecordsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AnswerRecordsClient)) +@mock.patch.object(AnswerRecordsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AnswerRecordsAsyncClient)) +def test_answer_records_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(AnswerRecordsClient, '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(AnswerRecordsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc", "true"), + (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc", "false"), + (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(AnswerRecordsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AnswerRecordsClient)) +@mock.patch.object(AnswerRecordsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AnswerRecordsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_answer_records_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc"), + (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_answer_records_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc"), + (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_answer_records_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_answer_records_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2.services.answer_records.transports.AnswerRecordsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AnswerRecordsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_answer_records(transport: str = 'grpc', request_type=answer_record.ListAnswerRecordsRequest): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_answer_records), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = answer_record.ListAnswerRecordsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_answer_records(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == answer_record.ListAnswerRecordsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAnswerRecordsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_answer_records_from_dict(): + test_list_answer_records(request_type=dict) + + +def test_list_answer_records_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnswerRecordsClient( + credentials=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_answer_records), + '__call__') as call: + client.list_answer_records() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == answer_record.ListAnswerRecordsRequest() + + +@pytest.mark.asyncio +async def test_list_answer_records_async(transport: str = 'grpc_asyncio', request_type=answer_record.ListAnswerRecordsRequest): + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_answer_records), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(answer_record.ListAnswerRecordsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_answer_records(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == answer_record.ListAnswerRecordsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAnswerRecordsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_answer_records_async_from_dict(): + await test_list_answer_records_async(request_type=dict) + + +def test_list_answer_records_field_headers(): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = answer_record.ListAnswerRecordsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_answer_records), + '__call__') as call: + call.return_value = answer_record.ListAnswerRecordsResponse() + client.list_answer_records(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_answer_records_field_headers_async(): + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = answer_record.ListAnswerRecordsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_answer_records), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(answer_record.ListAnswerRecordsResponse()) + await client.list_answer_records(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_answer_records_flattened(): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_answer_records), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = answer_record.ListAnswerRecordsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_answer_records( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_answer_records_flattened_error(): + client = AnswerRecordsClient( + credentials=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_answer_records( + answer_record.ListAnswerRecordsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_answer_records_flattened_async(): + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_answer_records), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = answer_record.ListAnswerRecordsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(answer_record.ListAnswerRecordsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_answer_records( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_answer_records_flattened_error_async(): + client = AnswerRecordsAsyncClient( + credentials=ga_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_answer_records( + answer_record.ListAnswerRecordsRequest(), + parent='parent_value', + ) + + +def test_list_answer_records_pager(): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_answer_records), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + answer_record.ListAnswerRecordsResponse( + answer_records=[ + answer_record.AnswerRecord(), + answer_record.AnswerRecord(), + answer_record.AnswerRecord(), + ], + next_page_token='abc', + ), + answer_record.ListAnswerRecordsResponse( + answer_records=[], + next_page_token='def', + ), + answer_record.ListAnswerRecordsResponse( + answer_records=[ + answer_record.AnswerRecord(), + ], + next_page_token='ghi', + ), + answer_record.ListAnswerRecordsResponse( + answer_records=[ + answer_record.AnswerRecord(), + answer_record.AnswerRecord(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_answer_records(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, answer_record.AnswerRecord) + for i in results) + +def test_list_answer_records_pages(): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_answer_records), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + answer_record.ListAnswerRecordsResponse( + answer_records=[ + answer_record.AnswerRecord(), + answer_record.AnswerRecord(), + answer_record.AnswerRecord(), + ], + next_page_token='abc', + ), + answer_record.ListAnswerRecordsResponse( + answer_records=[], + next_page_token='def', + ), + answer_record.ListAnswerRecordsResponse( + answer_records=[ + answer_record.AnswerRecord(), + ], + next_page_token='ghi', + ), + answer_record.ListAnswerRecordsResponse( + answer_records=[ + answer_record.AnswerRecord(), + answer_record.AnswerRecord(), + ], + ), + RuntimeError, + ) + pages = list(client.list_answer_records(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_answer_records_async_pager(): + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_answer_records), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + answer_record.ListAnswerRecordsResponse( + answer_records=[ + answer_record.AnswerRecord(), + answer_record.AnswerRecord(), + answer_record.AnswerRecord(), + ], + next_page_token='abc', + ), + answer_record.ListAnswerRecordsResponse( + answer_records=[], + next_page_token='def', + ), + answer_record.ListAnswerRecordsResponse( + answer_records=[ + answer_record.AnswerRecord(), + ], + next_page_token='ghi', + ), + answer_record.ListAnswerRecordsResponse( + answer_records=[ + answer_record.AnswerRecord(), + answer_record.AnswerRecord(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_answer_records(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, answer_record.AnswerRecord) + for i in responses) + +@pytest.mark.asyncio +async def test_list_answer_records_async_pages(): + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_answer_records), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + answer_record.ListAnswerRecordsResponse( + answer_records=[ + answer_record.AnswerRecord(), + answer_record.AnswerRecord(), + answer_record.AnswerRecord(), + ], + next_page_token='abc', + ), + answer_record.ListAnswerRecordsResponse( + answer_records=[], + next_page_token='def', + ), + answer_record.ListAnswerRecordsResponse( + answer_records=[ + answer_record.AnswerRecord(), + ], + next_page_token='ghi', + ), + answer_record.ListAnswerRecordsResponse( + answer_records=[ + answer_record.AnswerRecord(), + answer_record.AnswerRecord(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_answer_records(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_answer_record(transport: str = 'grpc', request_type=gcd_answer_record.UpdateAnswerRecordRequest): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_answer_record), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_answer_record.AnswerRecord( + name='name_value', + agent_assistant_record=gcd_answer_record.AgentAssistantRecord(article_suggestion_answer=participant.ArticleAnswer(title='title_value')), + ) + response = client.update_answer_record(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_answer_record.UpdateAnswerRecordRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_answer_record.AnswerRecord) + assert response.name == 'name_value' + + +def test_update_answer_record_from_dict(): + test_update_answer_record(request_type=dict) + + +def test_update_answer_record_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnswerRecordsClient( + credentials=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_answer_record), + '__call__') as call: + client.update_answer_record() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_answer_record.UpdateAnswerRecordRequest() + + +@pytest.mark.asyncio +async def test_update_answer_record_async(transport: str = 'grpc_asyncio', request_type=gcd_answer_record.UpdateAnswerRecordRequest): + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_answer_record), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_answer_record.AnswerRecord( + name='name_value', + )) + response = await client.update_answer_record(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_answer_record.UpdateAnswerRecordRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_answer_record.AnswerRecord) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_update_answer_record_async_from_dict(): + await test_update_answer_record_async(request_type=dict) + + +def test_update_answer_record_field_headers(): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_answer_record.UpdateAnswerRecordRequest() + + request.answer_record.name = 'answer_record.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_answer_record), + '__call__') as call: + call.return_value = gcd_answer_record.AnswerRecord() + client.update_answer_record(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'answer_record.name=answer_record.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_answer_record_field_headers_async(): + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_answer_record.UpdateAnswerRecordRequest() + + request.answer_record.name = 'answer_record.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_answer_record), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_answer_record.AnswerRecord()) + await client.update_answer_record(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'answer_record.name=answer_record.name/value', + ) in kw['metadata'] + + +def test_update_answer_record_flattened(): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_answer_record), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_answer_record.AnswerRecord() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_answer_record( + answer_record=gcd_answer_record.AnswerRecord(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].answer_record + mock_val = gcd_answer_record.AnswerRecord(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_answer_record_flattened_error(): + client = AnswerRecordsClient( + credentials=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_answer_record( + gcd_answer_record.UpdateAnswerRecordRequest(), + answer_record=gcd_answer_record.AnswerRecord(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_answer_record_flattened_async(): + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_answer_record), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_answer_record.AnswerRecord() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_answer_record.AnswerRecord()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_answer_record( + answer_record=gcd_answer_record.AnswerRecord(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].answer_record + mock_val = gcd_answer_record.AnswerRecord(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_answer_record_flattened_error_async(): + client = AnswerRecordsAsyncClient( + credentials=ga_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_answer_record( + gcd_answer_record.UpdateAnswerRecordRequest(), + answer_record=gcd_answer_record.AnswerRecord(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AnswerRecordsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AnswerRecordsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AnswerRecordsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AnswerRecordsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AnswerRecordsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AnswerRecordsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AnswerRecordsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AnswerRecordsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AnswerRecordsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AnswerRecordsGrpcTransport, + transports.AnswerRecordsGrpcAsyncIOTransport, +]) +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 = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AnswerRecordsGrpcTransport, + ) + +def test_answer_records_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AnswerRecordsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_answer_records_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2.services.answer_records.transports.AnswerRecordsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AnswerRecordsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_answer_records', + 'update_answer_record', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_answer_records_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.dialogflow_v2.services.answer_records.transports.AnswerRecordsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AnswerRecordsTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_answer_records_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.dialogflow_v2.services.answer_records.transports.AnswerRecordsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AnswerRecordsTransport() + adc.assert_called_once() + + +def test_answer_records_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) + AnswerRecordsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AnswerRecordsGrpcTransport, + transports.AnswerRecordsGrpcAsyncIOTransport, + ], +) +def test_answer_records_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AnswerRecordsGrpcTransport, grpc_helpers), + (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_answer_records_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AnswerRecordsGrpcTransport, transports.AnswerRecordsGrpcAsyncIOTransport]) +def test_answer_records_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_answer_records_host_no_port(): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_answer_records_host_with_port(): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_answer_records_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AnswerRecordsGrpcTransport( + 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_answer_records_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AnswerRecordsGrpcAsyncIOTransport( + 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.AnswerRecordsGrpcTransport, transports.AnswerRecordsGrpcAsyncIOTransport]) +def test_answer_records_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.AnswerRecordsGrpcTransport, transports.AnswerRecordsGrpcAsyncIOTransport]) +def test_answer_records_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_answer_record_path(): + project = "squid" + answer_record = "clam" + expected = "projects/{project}/answerRecords/{answer_record}".format(project=project, answer_record=answer_record, ) + actual = AnswerRecordsClient.answer_record_path(project, answer_record) + assert expected == actual + + +def test_parse_answer_record_path(): + expected = { + "project": "whelk", + "answer_record": "octopus", + } + path = AnswerRecordsClient.answer_record_path(**expected) + + # Check that the path construction is reversible. + actual = AnswerRecordsClient.parse_answer_record_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AnswerRecordsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = AnswerRecordsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AnswerRecordsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = AnswerRecordsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = AnswerRecordsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AnswerRecordsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AnswerRecordsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = AnswerRecordsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AnswerRecordsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = AnswerRecordsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = AnswerRecordsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AnswerRecordsClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = AnswerRecordsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = AnswerRecordsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AnswerRecordsClient.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.AnswerRecordsTransport, '_prep_wrapped_messages') as prep: + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AnswerRecordsTransport, '_prep_wrapped_messages') as prep: + transport_class = AnswerRecordsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_contexts.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_contexts.py new file mode 100644 index 000000000..d169cba56 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_contexts.py @@ -0,0 +1,2542 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.contexts import ContextsAsyncClient +from google.cloud.dialogflow_v2.services.contexts import ContextsClient +from google.cloud.dialogflow_v2.services.contexts import pagers +from google.cloud.dialogflow_v2.services.contexts import transports +from google.cloud.dialogflow_v2.types import context +from google.cloud.dialogflow_v2.types import context as gcd_context +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ContextsClient._get_default_mtls_endpoint(None) is None + assert ContextsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ContextsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ContextsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ContextsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ContextsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + ContextsClient, + ContextsAsyncClient, +]) +def test_contexts_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ContextsGrpcTransport, "grpc"), + (transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_contexts_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + ContextsClient, + ContextsAsyncClient, +]) +def test_contexts_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 == 'dialogflow.googleapis.com:443' + + +def test_contexts_client_get_transport_class(): + transport = ContextsClient.get_transport_class() + available_transports = [ + transports.ContextsGrpcTransport, + ] + assert transport in available_transports + + transport = ContextsClient.get_transport_class("grpc") + assert transport == transports.ContextsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ContextsClient, transports.ContextsGrpcTransport, "grpc"), + (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ContextsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ContextsClient)) +@mock.patch.object(ContextsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ContextsAsyncClient)) +def test_contexts_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(ContextsClient, '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(ContextsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ContextsClient, transports.ContextsGrpcTransport, "grpc", "true"), + (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ContextsClient, transports.ContextsGrpcTransport, "grpc", "false"), + (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ContextsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ContextsClient)) +@mock.patch.object(ContextsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ContextsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_contexts_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ContextsClient, transports.ContextsGrpcTransport, "grpc"), + (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_contexts_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ContextsClient, transports.ContextsGrpcTransport, "grpc"), + (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_contexts_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_contexts_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2.services.contexts.transports.ContextsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ContextsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_contexts(transport: str = 'grpc', request_type=context.ListContextsRequest): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_contexts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = context.ListContextsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_contexts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == context.ListContextsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListContextsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_contexts_from_dict(): + test_list_contexts(request_type=dict) + + +def test_list_contexts_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ContextsClient( + credentials=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_contexts), + '__call__') as call: + client.list_contexts() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == context.ListContextsRequest() + + +@pytest.mark.asyncio +async def test_list_contexts_async(transport: str = 'grpc_asyncio', request_type=context.ListContextsRequest): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_contexts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(context.ListContextsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_contexts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == context.ListContextsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListContextsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_contexts_async_from_dict(): + await test_list_contexts_async(request_type=dict) + + +def test_list_contexts_field_headers(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = context.ListContextsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_contexts), + '__call__') as call: + call.return_value = context.ListContextsResponse() + client.list_contexts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_contexts_field_headers_async(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = context.ListContextsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_contexts), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(context.ListContextsResponse()) + await client.list_contexts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_contexts_flattened(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_contexts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = context.ListContextsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_contexts( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_contexts_flattened_error(): + client = ContextsClient( + credentials=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_contexts( + context.ListContextsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_contexts_flattened_async(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_contexts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = context.ListContextsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(context.ListContextsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_contexts( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_contexts_flattened_error_async(): + client = ContextsAsyncClient( + credentials=ga_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_contexts( + context.ListContextsRequest(), + parent='parent_value', + ) + + +def test_list_contexts_pager(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_contexts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + context.ListContextsResponse( + contexts=[ + context.Context(), + context.Context(), + context.Context(), + ], + next_page_token='abc', + ), + context.ListContextsResponse( + contexts=[], + next_page_token='def', + ), + context.ListContextsResponse( + contexts=[ + context.Context(), + ], + next_page_token='ghi', + ), + context.ListContextsResponse( + contexts=[ + context.Context(), + context.Context(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_contexts(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, context.Context) + for i in results) + +def test_list_contexts_pages(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_contexts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + context.ListContextsResponse( + contexts=[ + context.Context(), + context.Context(), + context.Context(), + ], + next_page_token='abc', + ), + context.ListContextsResponse( + contexts=[], + next_page_token='def', + ), + context.ListContextsResponse( + contexts=[ + context.Context(), + ], + next_page_token='ghi', + ), + context.ListContextsResponse( + contexts=[ + context.Context(), + context.Context(), + ], + ), + RuntimeError, + ) + pages = list(client.list_contexts(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_contexts_async_pager(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_contexts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + context.ListContextsResponse( + contexts=[ + context.Context(), + context.Context(), + context.Context(), + ], + next_page_token='abc', + ), + context.ListContextsResponse( + contexts=[], + next_page_token='def', + ), + context.ListContextsResponse( + contexts=[ + context.Context(), + ], + next_page_token='ghi', + ), + context.ListContextsResponse( + contexts=[ + context.Context(), + context.Context(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_contexts(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, context.Context) + for i in responses) + +@pytest.mark.asyncio +async def test_list_contexts_async_pages(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_contexts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + context.ListContextsResponse( + contexts=[ + context.Context(), + context.Context(), + context.Context(), + ], + next_page_token='abc', + ), + context.ListContextsResponse( + contexts=[], + next_page_token='def', + ), + context.ListContextsResponse( + contexts=[ + context.Context(), + ], + next_page_token='ghi', + ), + context.ListContextsResponse( + contexts=[ + context.Context(), + context.Context(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_contexts(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_context(transport: str = 'grpc', request_type=context.GetContextRequest): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = context.Context( + name='name_value', + lifespan_count=1498, + ) + response = client.get_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == context.GetContextRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, context.Context) + assert response.name == 'name_value' + assert response.lifespan_count == 1498 + + +def test_get_context_from_dict(): + test_get_context(request_type=dict) + + +def test_get_context_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ContextsClient( + credentials=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_context), + '__call__') as call: + client.get_context() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == context.GetContextRequest() + + +@pytest.mark.asyncio +async def test_get_context_async(transport: str = 'grpc_asyncio', request_type=context.GetContextRequest): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(context.Context( + name='name_value', + lifespan_count=1498, + )) + response = await client.get_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == context.GetContextRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, context.Context) + assert response.name == 'name_value' + assert response.lifespan_count == 1498 + + +@pytest.mark.asyncio +async def test_get_context_async_from_dict(): + await test_get_context_async(request_type=dict) + + +def test_get_context_field_headers(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = context.GetContextRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_context), + '__call__') as call: + call.return_value = context.Context() + client.get_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_context_field_headers_async(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = context.GetContextRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_context), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(context.Context()) + await client.get_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_context_flattened(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = context.Context() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_context( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_context_flattened_error(): + client = ContextsClient( + credentials=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_context( + context.GetContextRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_context_flattened_async(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = context.Context() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(context.Context()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_context( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_context_flattened_error_async(): + client = ContextsAsyncClient( + credentials=ga_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_context( + context.GetContextRequest(), + name='name_value', + ) + + +def test_create_context(transport: str = 'grpc', request_type=gcd_context.CreateContextRequest): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_context.Context( + name='name_value', + lifespan_count=1498, + ) + response = client.create_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_context.CreateContextRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_context.Context) + assert response.name == 'name_value' + assert response.lifespan_count == 1498 + + +def test_create_context_from_dict(): + test_create_context(request_type=dict) + + +def test_create_context_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ContextsClient( + credentials=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_context), + '__call__') as call: + client.create_context() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_context.CreateContextRequest() + + +@pytest.mark.asyncio +async def test_create_context_async(transport: str = 'grpc_asyncio', request_type=gcd_context.CreateContextRequest): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context( + name='name_value', + lifespan_count=1498, + )) + response = await client.create_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_context.CreateContextRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_context.Context) + assert response.name == 'name_value' + assert response.lifespan_count == 1498 + + +@pytest.mark.asyncio +async def test_create_context_async_from_dict(): + await test_create_context_async(request_type=dict) + + +def test_create_context_field_headers(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_context.CreateContextRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_context), + '__call__') as call: + call.return_value = gcd_context.Context() + client.create_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_context_field_headers_async(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_context.CreateContextRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_context), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context()) + await client.create_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_context_flattened(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_context.Context() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_context( + parent='parent_value', + context=gcd_context.Context(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].context + mock_val = gcd_context.Context(name='name_value') + assert arg == mock_val + + +def test_create_context_flattened_error(): + client = ContextsClient( + credentials=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_context( + gcd_context.CreateContextRequest(), + parent='parent_value', + context=gcd_context.Context(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_context_flattened_async(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_context.Context() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_context( + parent='parent_value', + context=gcd_context.Context(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].context + mock_val = gcd_context.Context(name='name_value') + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_context_flattened_error_async(): + client = ContextsAsyncClient( + credentials=ga_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_context( + gcd_context.CreateContextRequest(), + parent='parent_value', + context=gcd_context.Context(name='name_value'), + ) + + +def test_update_context(transport: str = 'grpc', request_type=gcd_context.UpdateContextRequest): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_context.Context( + name='name_value', + lifespan_count=1498, + ) + response = client.update_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_context.UpdateContextRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_context.Context) + assert response.name == 'name_value' + assert response.lifespan_count == 1498 + + +def test_update_context_from_dict(): + test_update_context(request_type=dict) + + +def test_update_context_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ContextsClient( + credentials=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_context), + '__call__') as call: + client.update_context() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_context.UpdateContextRequest() + + +@pytest.mark.asyncio +async def test_update_context_async(transport: str = 'grpc_asyncio', request_type=gcd_context.UpdateContextRequest): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context( + name='name_value', + lifespan_count=1498, + )) + response = await client.update_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_context.UpdateContextRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_context.Context) + assert response.name == 'name_value' + assert response.lifespan_count == 1498 + + +@pytest.mark.asyncio +async def test_update_context_async_from_dict(): + await test_update_context_async(request_type=dict) + + +def test_update_context_field_headers(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_context.UpdateContextRequest() + + request.context.name = 'context.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_context), + '__call__') as call: + call.return_value = gcd_context.Context() + client.update_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'context.name=context.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_context_field_headers_async(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_context.UpdateContextRequest() + + request.context.name = 'context.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_context), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context()) + await client.update_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'context.name=context.name/value', + ) in kw['metadata'] + + +def test_update_context_flattened(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_context.Context() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_context( + context=gcd_context.Context(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].context + mock_val = gcd_context.Context(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_context_flattened_error(): + client = ContextsClient( + credentials=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_context( + gcd_context.UpdateContextRequest(), + context=gcd_context.Context(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_context_flattened_async(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_context.Context() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_context( + context=gcd_context.Context(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].context + mock_val = gcd_context.Context(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_context_flattened_error_async(): + client = ContextsAsyncClient( + credentials=ga_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_context( + gcd_context.UpdateContextRequest(), + context=gcd_context.Context(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_context(transport: str = 'grpc', request_type=context.DeleteContextRequest): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == context.DeleteContextRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_context_from_dict(): + test_delete_context(request_type=dict) + + +def test_delete_context_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ContextsClient( + credentials=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_context), + '__call__') as call: + client.delete_context() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == context.DeleteContextRequest() + + +@pytest.mark.asyncio +async def test_delete_context_async(transport: str = 'grpc_asyncio', request_type=context.DeleteContextRequest): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == context.DeleteContextRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_context_async_from_dict(): + await test_delete_context_async(request_type=dict) + + +def test_delete_context_field_headers(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = context.DeleteContextRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_context), + '__call__') as call: + call.return_value = None + client.delete_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_context_field_headers_async(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = context.DeleteContextRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_context), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_context_flattened(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_context), + '__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_context( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_context_flattened_error(): + client = ContextsClient( + credentials=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_context( + context.DeleteContextRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_context_flattened_async(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_context), + '__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_context( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_context_flattened_error_async(): + client = ContextsAsyncClient( + credentials=ga_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_context( + context.DeleteContextRequest(), + name='name_value', + ) + + +def test_delete_all_contexts(transport: str = 'grpc', request_type=context.DeleteAllContextsRequest): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_all_contexts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_all_contexts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == context.DeleteAllContextsRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_all_contexts_from_dict(): + test_delete_all_contexts(request_type=dict) + + +def test_delete_all_contexts_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ContextsClient( + credentials=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_all_contexts), + '__call__') as call: + client.delete_all_contexts() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == context.DeleteAllContextsRequest() + + +@pytest.mark.asyncio +async def test_delete_all_contexts_async(transport: str = 'grpc_asyncio', request_type=context.DeleteAllContextsRequest): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_all_contexts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_all_contexts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == context.DeleteAllContextsRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_all_contexts_async_from_dict(): + await test_delete_all_contexts_async(request_type=dict) + + +def test_delete_all_contexts_field_headers(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = context.DeleteAllContextsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_all_contexts), + '__call__') as call: + call.return_value = None + client.delete_all_contexts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_delete_all_contexts_field_headers_async(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = context.DeleteAllContextsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_all_contexts), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_all_contexts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_delete_all_contexts_flattened(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_all_contexts), + '__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_all_contexts( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_delete_all_contexts_flattened_error(): + client = ContextsClient( + credentials=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_all_contexts( + context.DeleteAllContextsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_delete_all_contexts_flattened_async(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_all_contexts), + '__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_all_contexts( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_all_contexts_flattened_error_async(): + client = ContextsAsyncClient( + credentials=ga_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_all_contexts( + context.DeleteAllContextsRequest(), + parent='parent_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ContextsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ContextsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ContextsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ContextsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ContextsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ContextsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ContextsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ContextsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ContextsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ContextsGrpcTransport, + transports.ContextsGrpcAsyncIOTransport, +]) +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 = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ContextsGrpcTransport, + ) + +def test_contexts_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ContextsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_contexts_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2.services.contexts.transports.ContextsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ContextsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_contexts', + 'get_context', + 'create_context', + 'update_context', + 'delete_context', + 'delete_all_contexts', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_contexts_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.dialogflow_v2.services.contexts.transports.ContextsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ContextsTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_contexts_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.dialogflow_v2.services.contexts.transports.ContextsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ContextsTransport() + adc.assert_called_once() + + +def test_contexts_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) + ContextsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ContextsGrpcTransport, + transports.ContextsGrpcAsyncIOTransport, + ], +) +def test_contexts_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ContextsGrpcTransport, grpc_helpers), + (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_contexts_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ContextsGrpcTransport, transports.ContextsGrpcAsyncIOTransport]) +def test_contexts_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_contexts_host_no_port(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_contexts_host_with_port(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_contexts_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ContextsGrpcTransport( + 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_contexts_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ContextsGrpcAsyncIOTransport( + 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.ContextsGrpcTransport, transports.ContextsGrpcAsyncIOTransport]) +def test_contexts_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.ContextsGrpcTransport, transports.ContextsGrpcAsyncIOTransport]) +def test_contexts_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_context_path(): + project = "squid" + session = "clam" + context = "whelk" + expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) + actual = ContextsClient.context_path(project, session, context) + assert expected == actual + + +def test_parse_context_path(): + expected = { + "project": "octopus", + "session": "oyster", + "context": "nudibranch", + } + path = ContextsClient.context_path(**expected) + + # Check that the path construction is reversible. + actual = ContextsClient.parse_context_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ContextsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = ContextsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ContextsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = ContextsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = ContextsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ContextsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ContextsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = ContextsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ContextsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = ContextsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = ContextsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ContextsClient.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 = ContextsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = ContextsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ContextsClient.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.ContextsTransport, '_prep_wrapped_messages') as prep: + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ContextsTransport, '_prep_wrapped_messages') as prep: + transport_class = ContextsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversation_profiles.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversation_profiles.py new file mode 100644 index 000000000..67da37e25 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversation_profiles.py @@ -0,0 +1,2446 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.conversation_profiles import ConversationProfilesAsyncClient +from google.cloud.dialogflow_v2.services.conversation_profiles import ConversationProfilesClient +from google.cloud.dialogflow_v2.services.conversation_profiles import pagers +from google.cloud.dialogflow_v2.services.conversation_profiles import transports +from google.cloud.dialogflow_v2.types import audio_config +from google.cloud.dialogflow_v2.types import conversation_profile +from google.cloud.dialogflow_v2.types import conversation_profile as gcd_conversation_profile +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ConversationProfilesClient._get_default_mtls_endpoint(None) is None + assert ConversationProfilesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ConversationProfilesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ConversationProfilesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ConversationProfilesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ConversationProfilesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + ConversationProfilesClient, + ConversationProfilesAsyncClient, +]) +def test_conversation_profiles_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ConversationProfilesGrpcTransport, "grpc"), + (transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_conversation_profiles_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + ConversationProfilesClient, + ConversationProfilesAsyncClient, +]) +def test_conversation_profiles_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 == 'dialogflow.googleapis.com:443' + + +def test_conversation_profiles_client_get_transport_class(): + transport = ConversationProfilesClient.get_transport_class() + available_transports = [ + transports.ConversationProfilesGrpcTransport, + ] + assert transport in available_transports + + transport = ConversationProfilesClient.get_transport_class("grpc") + assert transport == transports.ConversationProfilesGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc"), + (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ConversationProfilesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationProfilesClient)) +@mock.patch.object(ConversationProfilesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationProfilesAsyncClient)) +def test_conversation_profiles_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(ConversationProfilesClient, '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(ConversationProfilesClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc", "true"), + (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc", "false"), + (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ConversationProfilesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationProfilesClient)) +@mock.patch.object(ConversationProfilesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationProfilesAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_conversation_profiles_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc"), + (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_conversation_profiles_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc"), + (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_conversation_profiles_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_conversation_profiles_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2.services.conversation_profiles.transports.ConversationProfilesGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ConversationProfilesClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_conversation_profiles(transport: str = 'grpc', request_type=conversation_profile.ListConversationProfilesRequest): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation_profiles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation_profile.ListConversationProfilesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_conversation_profiles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == conversation_profile.ListConversationProfilesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversationProfilesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_conversation_profiles_from_dict(): + test_list_conversation_profiles(request_type=dict) + + +def test_list_conversation_profiles_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationProfilesClient( + credentials=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_conversation_profiles), + '__call__') as call: + client.list_conversation_profiles() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversation_profile.ListConversationProfilesRequest() + + +@pytest.mark.asyncio +async def test_list_conversation_profiles_async(transport: str = 'grpc_asyncio', request_type=conversation_profile.ListConversationProfilesRequest): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation_profiles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation_profile.ListConversationProfilesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_conversation_profiles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversation_profile.ListConversationProfilesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversationProfilesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_conversation_profiles_async_from_dict(): + await test_list_conversation_profiles_async(request_type=dict) + + +def test_list_conversation_profiles_field_headers(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation_profile.ListConversationProfilesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversation_profiles), + '__call__') as call: + call.return_value = conversation_profile.ListConversationProfilesResponse() + client.list_conversation_profiles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_conversation_profiles_field_headers_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation_profile.ListConversationProfilesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversation_profiles), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation_profile.ListConversationProfilesResponse()) + await client.list_conversation_profiles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_conversation_profiles_flattened(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversation_profiles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation_profile.ListConversationProfilesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_conversation_profiles( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_conversation_profiles_flattened_error(): + client = ConversationProfilesClient( + credentials=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_conversation_profiles( + conversation_profile.ListConversationProfilesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_conversation_profiles_flattened_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversation_profiles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation_profile.ListConversationProfilesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation_profile.ListConversationProfilesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_conversation_profiles( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_conversation_profiles_flattened_error_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_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_conversation_profiles( + conversation_profile.ListConversationProfilesRequest(), + parent='parent_value', + ) + + +def test_list_conversation_profiles_pager(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversation_profiles), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[ + conversation_profile.ConversationProfile(), + conversation_profile.ConversationProfile(), + conversation_profile.ConversationProfile(), + ], + next_page_token='abc', + ), + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[], + next_page_token='def', + ), + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[ + conversation_profile.ConversationProfile(), + ], + next_page_token='ghi', + ), + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[ + conversation_profile.ConversationProfile(), + conversation_profile.ConversationProfile(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_conversation_profiles(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, conversation_profile.ConversationProfile) + for i in results) + +def test_list_conversation_profiles_pages(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversation_profiles), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[ + conversation_profile.ConversationProfile(), + conversation_profile.ConversationProfile(), + conversation_profile.ConversationProfile(), + ], + next_page_token='abc', + ), + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[], + next_page_token='def', + ), + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[ + conversation_profile.ConversationProfile(), + ], + next_page_token='ghi', + ), + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[ + conversation_profile.ConversationProfile(), + conversation_profile.ConversationProfile(), + ], + ), + RuntimeError, + ) + pages = list(client.list_conversation_profiles(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_conversation_profiles_async_pager(): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversation_profiles), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[ + conversation_profile.ConversationProfile(), + conversation_profile.ConversationProfile(), + conversation_profile.ConversationProfile(), + ], + next_page_token='abc', + ), + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[], + next_page_token='def', + ), + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[ + conversation_profile.ConversationProfile(), + ], + next_page_token='ghi', + ), + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[ + conversation_profile.ConversationProfile(), + conversation_profile.ConversationProfile(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_conversation_profiles(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, conversation_profile.ConversationProfile) + for i in responses) + +@pytest.mark.asyncio +async def test_list_conversation_profiles_async_pages(): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversation_profiles), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[ + conversation_profile.ConversationProfile(), + conversation_profile.ConversationProfile(), + conversation_profile.ConversationProfile(), + ], + next_page_token='abc', + ), + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[], + next_page_token='def', + ), + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[ + conversation_profile.ConversationProfile(), + ], + next_page_token='ghi', + ), + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[ + conversation_profile.ConversationProfile(), + conversation_profile.ConversationProfile(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_conversation_profiles(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_conversation_profile(transport: str = 'grpc', request_type=conversation_profile.GetConversationProfileRequest): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation_profile.ConversationProfile( + name='name_value', + display_name='display_name_value', + language_code='language_code_value', + time_zone='time_zone_value', + security_settings='security_settings_value', + ) + response = client.get_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == conversation_profile.GetConversationProfileRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, conversation_profile.ConversationProfile) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.language_code == 'language_code_value' + assert response.time_zone == 'time_zone_value' + assert response.security_settings == 'security_settings_value' + + +def test_get_conversation_profile_from_dict(): + test_get_conversation_profile(request_type=dict) + + +def test_get_conversation_profile_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationProfilesClient( + credentials=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_conversation_profile), + '__call__') as call: + client.get_conversation_profile() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversation_profile.GetConversationProfileRequest() + + +@pytest.mark.asyncio +async def test_get_conversation_profile_async(transport: str = 'grpc_asyncio', request_type=conversation_profile.GetConversationProfileRequest): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation_profile.ConversationProfile( + name='name_value', + display_name='display_name_value', + language_code='language_code_value', + time_zone='time_zone_value', + security_settings='security_settings_value', + )) + response = await client.get_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversation_profile.GetConversationProfileRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, conversation_profile.ConversationProfile) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.language_code == 'language_code_value' + assert response.time_zone == 'time_zone_value' + assert response.security_settings == 'security_settings_value' + + +@pytest.mark.asyncio +async def test_get_conversation_profile_async_from_dict(): + await test_get_conversation_profile_async(request_type=dict) + + +def test_get_conversation_profile_field_headers(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation_profile.GetConversationProfileRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation_profile), + '__call__') as call: + call.return_value = conversation_profile.ConversationProfile() + client.get_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_conversation_profile_field_headers_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation_profile.GetConversationProfileRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation_profile), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation_profile.ConversationProfile()) + await client.get_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_conversation_profile_flattened(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation_profile.ConversationProfile() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_conversation_profile( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_conversation_profile_flattened_error(): + client = ConversationProfilesClient( + credentials=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_conversation_profile( + conversation_profile.GetConversationProfileRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_conversation_profile_flattened_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation_profile.ConversationProfile() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation_profile.ConversationProfile()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_conversation_profile( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_conversation_profile_flattened_error_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_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_conversation_profile( + conversation_profile.GetConversationProfileRequest(), + name='name_value', + ) + + +def test_create_conversation_profile(transport: str = 'grpc', request_type=gcd_conversation_profile.CreateConversationProfileRequest): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation_profile.ConversationProfile( + name='name_value', + display_name='display_name_value', + language_code='language_code_value', + time_zone='time_zone_value', + security_settings='security_settings_value', + ) + response = client.create_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_conversation_profile.CreateConversationProfileRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation_profile.ConversationProfile) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.language_code == 'language_code_value' + assert response.time_zone == 'time_zone_value' + assert response.security_settings == 'security_settings_value' + + +def test_create_conversation_profile_from_dict(): + test_create_conversation_profile(request_type=dict) + + +def test_create_conversation_profile_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationProfilesClient( + credentials=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_conversation_profile), + '__call__') as call: + client.create_conversation_profile() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_conversation_profile.CreateConversationProfileRequest() + + +@pytest.mark.asyncio +async def test_create_conversation_profile_async(transport: str = 'grpc_asyncio', request_type=gcd_conversation_profile.CreateConversationProfileRequest): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation_profile.ConversationProfile( + name='name_value', + display_name='display_name_value', + language_code='language_code_value', + time_zone='time_zone_value', + security_settings='security_settings_value', + )) + response = await client.create_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_conversation_profile.CreateConversationProfileRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation_profile.ConversationProfile) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.language_code == 'language_code_value' + assert response.time_zone == 'time_zone_value' + assert response.security_settings == 'security_settings_value' + + +@pytest.mark.asyncio +async def test_create_conversation_profile_async_from_dict(): + await test_create_conversation_profile_async(request_type=dict) + + +def test_create_conversation_profile_field_headers(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_conversation_profile.CreateConversationProfileRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation_profile), + '__call__') as call: + call.return_value = gcd_conversation_profile.ConversationProfile() + client.create_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_conversation_profile_field_headers_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_conversation_profile.CreateConversationProfileRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation_profile), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation_profile.ConversationProfile()) + await client.create_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_conversation_profile_flattened(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation_profile.ConversationProfile() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_conversation_profile( + parent='parent_value', + conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].conversation_profile + mock_val = gcd_conversation_profile.ConversationProfile(name='name_value') + assert arg == mock_val + + +def test_create_conversation_profile_flattened_error(): + client = ConversationProfilesClient( + credentials=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_conversation_profile( + gcd_conversation_profile.CreateConversationProfileRequest(), + parent='parent_value', + conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_conversation_profile_flattened_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation_profile.ConversationProfile() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation_profile.ConversationProfile()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_conversation_profile( + parent='parent_value', + conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].conversation_profile + mock_val = gcd_conversation_profile.ConversationProfile(name='name_value') + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_conversation_profile_flattened_error_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_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_conversation_profile( + gcd_conversation_profile.CreateConversationProfileRequest(), + parent='parent_value', + conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), + ) + + +def test_update_conversation_profile(transport: str = 'grpc', request_type=gcd_conversation_profile.UpdateConversationProfileRequest): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation_profile.ConversationProfile( + name='name_value', + display_name='display_name_value', + language_code='language_code_value', + time_zone='time_zone_value', + security_settings='security_settings_value', + ) + response = client.update_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_conversation_profile.UpdateConversationProfileRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation_profile.ConversationProfile) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.language_code == 'language_code_value' + assert response.time_zone == 'time_zone_value' + assert response.security_settings == 'security_settings_value' + + +def test_update_conversation_profile_from_dict(): + test_update_conversation_profile(request_type=dict) + + +def test_update_conversation_profile_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationProfilesClient( + credentials=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_conversation_profile), + '__call__') as call: + client.update_conversation_profile() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_conversation_profile.UpdateConversationProfileRequest() + + +@pytest.mark.asyncio +async def test_update_conversation_profile_async(transport: str = 'grpc_asyncio', request_type=gcd_conversation_profile.UpdateConversationProfileRequest): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation_profile.ConversationProfile( + name='name_value', + display_name='display_name_value', + language_code='language_code_value', + time_zone='time_zone_value', + security_settings='security_settings_value', + )) + response = await client.update_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_conversation_profile.UpdateConversationProfileRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation_profile.ConversationProfile) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.language_code == 'language_code_value' + assert response.time_zone == 'time_zone_value' + assert response.security_settings == 'security_settings_value' + + +@pytest.mark.asyncio +async def test_update_conversation_profile_async_from_dict(): + await test_update_conversation_profile_async(request_type=dict) + + +def test_update_conversation_profile_field_headers(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_conversation_profile.UpdateConversationProfileRequest() + + request.conversation_profile.name = 'conversation_profile.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation_profile), + '__call__') as call: + call.return_value = gcd_conversation_profile.ConversationProfile() + client.update_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'conversation_profile.name=conversation_profile.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_conversation_profile_field_headers_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_conversation_profile.UpdateConversationProfileRequest() + + request.conversation_profile.name = 'conversation_profile.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation_profile), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation_profile.ConversationProfile()) + await client.update_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'conversation_profile.name=conversation_profile.name/value', + ) in kw['metadata'] + + +def test_update_conversation_profile_flattened(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation_profile.ConversationProfile() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_conversation_profile( + conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].conversation_profile + mock_val = gcd_conversation_profile.ConversationProfile(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_conversation_profile_flattened_error(): + client = ConversationProfilesClient( + credentials=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_conversation_profile( + gcd_conversation_profile.UpdateConversationProfileRequest(), + conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_conversation_profile_flattened_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation_profile.ConversationProfile() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation_profile.ConversationProfile()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_conversation_profile( + conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].conversation_profile + mock_val = gcd_conversation_profile.ConversationProfile(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_conversation_profile_flattened_error_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_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_conversation_profile( + gcd_conversation_profile.UpdateConversationProfileRequest(), + conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_conversation_profile(transport: str = 'grpc', request_type=conversation_profile.DeleteConversationProfileRequest): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == conversation_profile.DeleteConversationProfileRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_conversation_profile_from_dict(): + test_delete_conversation_profile(request_type=dict) + + +def test_delete_conversation_profile_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationProfilesClient( + credentials=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_conversation_profile), + '__call__') as call: + client.delete_conversation_profile() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversation_profile.DeleteConversationProfileRequest() + + +@pytest.mark.asyncio +async def test_delete_conversation_profile_async(transport: str = 'grpc_asyncio', request_type=conversation_profile.DeleteConversationProfileRequest): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversation_profile.DeleteConversationProfileRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_conversation_profile_async_from_dict(): + await test_delete_conversation_profile_async(request_type=dict) + + +def test_delete_conversation_profile_field_headers(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation_profile.DeleteConversationProfileRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation_profile), + '__call__') as call: + call.return_value = None + client.delete_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_conversation_profile_field_headers_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation_profile.DeleteConversationProfileRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation_profile), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_conversation_profile_flattened(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation_profile), + '__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_conversation_profile( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_conversation_profile_flattened_error(): + client = ConversationProfilesClient( + credentials=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_conversation_profile( + conversation_profile.DeleteConversationProfileRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_conversation_profile_flattened_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation_profile), + '__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_conversation_profile( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_conversation_profile_flattened_error_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_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_conversation_profile( + conversation_profile.DeleteConversationProfileRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ConversationProfilesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ConversationProfilesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConversationProfilesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ConversationProfilesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConversationProfilesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ConversationProfilesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ConversationProfilesClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ConversationProfilesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ConversationProfilesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ConversationProfilesGrpcTransport, + transports.ConversationProfilesGrpcAsyncIOTransport, +]) +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 = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ConversationProfilesGrpcTransport, + ) + +def test_conversation_profiles_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ConversationProfilesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_conversation_profiles_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2.services.conversation_profiles.transports.ConversationProfilesTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ConversationProfilesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_conversation_profiles', + 'get_conversation_profile', + 'create_conversation_profile', + 'update_conversation_profile', + 'delete_conversation_profile', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_conversation_profiles_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.dialogflow_v2.services.conversation_profiles.transports.ConversationProfilesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConversationProfilesTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_conversation_profiles_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.dialogflow_v2.services.conversation_profiles.transports.ConversationProfilesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConversationProfilesTransport() + adc.assert_called_once() + + +def test_conversation_profiles_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) + ConversationProfilesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ConversationProfilesGrpcTransport, + transports.ConversationProfilesGrpcAsyncIOTransport, + ], +) +def test_conversation_profiles_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationProfilesGrpcTransport, grpc_helpers), + (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_conversation_profiles_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ConversationProfilesGrpcTransport, transports.ConversationProfilesGrpcAsyncIOTransport]) +def test_conversation_profiles_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_conversation_profiles_host_no_port(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_conversation_profiles_host_with_port(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_conversation_profiles_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ConversationProfilesGrpcTransport( + 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_conversation_profiles_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ConversationProfilesGrpcAsyncIOTransport( + 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.ConversationProfilesGrpcTransport, transports.ConversationProfilesGrpcAsyncIOTransport]) +def test_conversation_profiles_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.ConversationProfilesGrpcTransport, transports.ConversationProfilesGrpcAsyncIOTransport]) +def test_conversation_profiles_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_agent_path(): + project = "squid" + expected = "projects/{project}/agent".format(project=project, ) + actual = ConversationProfilesClient.agent_path(project) + assert expected == actual + + +def test_parse_agent_path(): + expected = { + "project": "clam", + } + path = ConversationProfilesClient.agent_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationProfilesClient.parse_agent_path(path) + assert expected == actual + +def test_conversation_model_path(): + project = "whelk" + location = "octopus" + conversation_model = "oyster" + expected = "projects/{project}/locations/{location}/conversationModels/{conversation_model}".format(project=project, location=location, conversation_model=conversation_model, ) + actual = ConversationProfilesClient.conversation_model_path(project, location, conversation_model) + assert expected == actual + + +def test_parse_conversation_model_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "conversation_model": "mussel", + } + path = ConversationProfilesClient.conversation_model_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationProfilesClient.parse_conversation_model_path(path) + assert expected == actual + +def test_conversation_profile_path(): + project = "winkle" + conversation_profile = "nautilus" + expected = "projects/{project}/conversationProfiles/{conversation_profile}".format(project=project, conversation_profile=conversation_profile, ) + actual = ConversationProfilesClient.conversation_profile_path(project, conversation_profile) + assert expected == actual + + +def test_parse_conversation_profile_path(): + expected = { + "project": "scallop", + "conversation_profile": "abalone", + } + path = ConversationProfilesClient.conversation_profile_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationProfilesClient.parse_conversation_profile_path(path) + assert expected == actual + +def test_cx_security_settings_path(): + project = "squid" + location = "clam" + security_settings = "whelk" + expected = "projects/{project}/locations/{location}/securitySettings/{security_settings}".format(project=project, location=location, security_settings=security_settings, ) + actual = ConversationProfilesClient.cx_security_settings_path(project, location, security_settings) + assert expected == actual + + +def test_parse_cx_security_settings_path(): + expected = { + "project": "octopus", + "location": "oyster", + "security_settings": "nudibranch", + } + path = ConversationProfilesClient.cx_security_settings_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationProfilesClient.parse_cx_security_settings_path(path) + assert expected == actual + +def test_document_path(): + project = "cuttlefish" + knowledge_base = "mussel" + document = "winkle" + expected = "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format(project=project, knowledge_base=knowledge_base, document=document, ) + actual = ConversationProfilesClient.document_path(project, knowledge_base, document) + assert expected == actual + + +def test_parse_document_path(): + expected = { + "project": "nautilus", + "knowledge_base": "scallop", + "document": "abalone", + } + path = ConversationProfilesClient.document_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationProfilesClient.parse_document_path(path) + assert expected == actual + +def test_knowledge_base_path(): + project = "squid" + knowledge_base = "clam" + expected = "projects/{project}/knowledgeBases/{knowledge_base}".format(project=project, knowledge_base=knowledge_base, ) + actual = ConversationProfilesClient.knowledge_base_path(project, knowledge_base) + assert expected == actual + + +def test_parse_knowledge_base_path(): + expected = { + "project": "whelk", + "knowledge_base": "octopus", + } + path = ConversationProfilesClient.knowledge_base_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationProfilesClient.parse_knowledge_base_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ConversationProfilesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = ConversationProfilesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationProfilesClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = ConversationProfilesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = ConversationProfilesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationProfilesClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ConversationProfilesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = ConversationProfilesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationProfilesClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = ConversationProfilesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = ConversationProfilesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationProfilesClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ConversationProfilesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = ConversationProfilesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationProfilesClient.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.ConversationProfilesTransport, '_prep_wrapped_messages') as prep: + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ConversationProfilesTransport, '_prep_wrapped_messages') as prep: + transport_class = ConversationProfilesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversations.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversations.py new file mode 100644 index 000000000..da9dd74b8 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversations.py @@ -0,0 +1,2557 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.conversations import ConversationsAsyncClient +from google.cloud.dialogflow_v2.services.conversations import ConversationsClient +from google.cloud.dialogflow_v2.services.conversations import pagers +from google.cloud.dialogflow_v2.services.conversations import transports +from google.cloud.dialogflow_v2.types import conversation +from google.cloud.dialogflow_v2.types import conversation as gcd_conversation +from google.cloud.dialogflow_v2.types import participant +from google.oauth2 import service_account +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ConversationsClient._get_default_mtls_endpoint(None) is None + assert ConversationsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ConversationsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ConversationsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ConversationsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ConversationsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + ConversationsClient, + ConversationsAsyncClient, +]) +def test_conversations_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ConversationsGrpcTransport, "grpc"), + (transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_conversations_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + ConversationsClient, + ConversationsAsyncClient, +]) +def test_conversations_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 == 'dialogflow.googleapis.com:443' + + +def test_conversations_client_get_transport_class(): + transport = ConversationsClient.get_transport_class() + available_transports = [ + transports.ConversationsGrpcTransport, + ] + assert transport in available_transports + + transport = ConversationsClient.get_transport_class("grpc") + assert transport == transports.ConversationsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversationsClient, transports.ConversationsGrpcTransport, "grpc"), + (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ConversationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationsClient)) +@mock.patch.object(ConversationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationsAsyncClient)) +def test_conversations_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(ConversationsClient, '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(ConversationsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ConversationsClient, transports.ConversationsGrpcTransport, "grpc", "true"), + (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ConversationsClient, transports.ConversationsGrpcTransport, "grpc", "false"), + (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ConversationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationsClient)) +@mock.patch.object(ConversationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_conversations_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversationsClient, transports.ConversationsGrpcTransport, "grpc"), + (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_conversations_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversationsClient, transports.ConversationsGrpcTransport, "grpc"), + (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_conversations_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_conversations_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2.services.conversations.transports.ConversationsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ConversationsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_create_conversation(transport: str = 'grpc', request_type=gcd_conversation.CreateConversationRequest): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation.Conversation( + name='name_value', + lifecycle_state=gcd_conversation.Conversation.LifecycleState.IN_PROGRESS, + conversation_profile='conversation_profile_value', + conversation_stage=gcd_conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, + ) + response = client.create_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_conversation.CreateConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation.Conversation) + assert response.name == 'name_value' + assert response.lifecycle_state == gcd_conversation.Conversation.LifecycleState.IN_PROGRESS + assert response.conversation_profile == 'conversation_profile_value' + assert response.conversation_stage == gcd_conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE + + +def test_create_conversation_from_dict(): + test_create_conversation(request_type=dict) + + +def test_create_conversation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationsClient( + credentials=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_conversation), + '__call__') as call: + client.create_conversation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_conversation.CreateConversationRequest() + + +@pytest.mark.asyncio +async def test_create_conversation_async(transport: str = 'grpc_asyncio', request_type=gcd_conversation.CreateConversationRequest): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation( + name='name_value', + lifecycle_state=gcd_conversation.Conversation.LifecycleState.IN_PROGRESS, + conversation_profile='conversation_profile_value', + conversation_stage=gcd_conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, + )) + response = await client.create_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_conversation.CreateConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation.Conversation) + assert response.name == 'name_value' + assert response.lifecycle_state == gcd_conversation.Conversation.LifecycleState.IN_PROGRESS + assert response.conversation_profile == 'conversation_profile_value' + assert response.conversation_stage == gcd_conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE + + +@pytest.mark.asyncio +async def test_create_conversation_async_from_dict(): + await test_create_conversation_async(request_type=dict) + + +def test_create_conversation_field_headers(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_conversation.CreateConversationRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation), + '__call__') as call: + call.return_value = gcd_conversation.Conversation() + client.create_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_conversation_field_headers_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_conversation.CreateConversationRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation()) + await client.create_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_conversation_flattened(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation.Conversation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_conversation( + parent='parent_value', + conversation=gcd_conversation.Conversation(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].conversation + mock_val = gcd_conversation.Conversation(name='name_value') + assert arg == mock_val + + +def test_create_conversation_flattened_error(): + client = ConversationsClient( + credentials=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_conversation( + gcd_conversation.CreateConversationRequest(), + parent='parent_value', + conversation=gcd_conversation.Conversation(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_conversation_flattened_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation.Conversation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_conversation( + parent='parent_value', + conversation=gcd_conversation.Conversation(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].conversation + mock_val = gcd_conversation.Conversation(name='name_value') + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_conversation_flattened_error_async(): + client = ConversationsAsyncClient( + credentials=ga_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_conversation( + gcd_conversation.CreateConversationRequest(), + parent='parent_value', + conversation=gcd_conversation.Conversation(name='name_value'), + ) + + +def test_list_conversations(transport: str = 'grpc', request_type=conversation.ListConversationsRequest): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.ListConversationsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.ListConversationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversationsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_conversations_from_dict(): + test_list_conversations(request_type=dict) + + +def test_list_conversations_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationsClient( + credentials=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_conversations), + '__call__') as call: + client.list_conversations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.ListConversationsRequest() + + +@pytest.mark.asyncio +async def test_list_conversations_async(transport: str = 'grpc_asyncio', request_type=conversation.ListConversationsRequest): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation.ListConversationsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.ListConversationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversationsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_conversations_async_from_dict(): + await test_list_conversations_async(request_type=dict) + + +def test_list_conversations_field_headers(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation.ListConversationsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + call.return_value = conversation.ListConversationsResponse() + client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_conversations_field_headers_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation.ListConversationsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.ListConversationsResponse()) + await client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_conversations_flattened(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.ListConversationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_conversations( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_conversations_flattened_error(): + client = ConversationsClient( + credentials=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_conversations( + conversation.ListConversationsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_conversations_flattened_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.ListConversationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.ListConversationsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_conversations( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_conversations_flattened_error_async(): + client = ConversationsAsyncClient( + credentials=ga_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_conversations( + conversation.ListConversationsRequest(), + parent='parent_value', + ) + + +def test_list_conversations_pager(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + conversation.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token='abc', + ), + conversation.ListConversationsResponse( + conversations=[], + next_page_token='def', + ), + conversation.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token='ghi', + ), + conversation.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_conversations(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, conversation.Conversation) + for i in results) + +def test_list_conversations_pages(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + conversation.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token='abc', + ), + conversation.ListConversationsResponse( + conversations=[], + next_page_token='def', + ), + conversation.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token='ghi', + ), + conversation.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_conversations(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_conversations_async_pager(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + conversation.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token='abc', + ), + conversation.ListConversationsResponse( + conversations=[], + next_page_token='def', + ), + conversation.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token='ghi', + ), + conversation.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_conversations(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, conversation.Conversation) + for i in responses) + +@pytest.mark.asyncio +async def test_list_conversations_async_pages(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + conversation.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token='abc', + ), + conversation.ListConversationsResponse( + conversations=[], + next_page_token='def', + ), + conversation.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token='ghi', + ), + conversation.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_conversations(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_conversation(transport: str = 'grpc', request_type=conversation.GetConversationRequest): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.Conversation( + name='name_value', + lifecycle_state=conversation.Conversation.LifecycleState.IN_PROGRESS, + conversation_profile='conversation_profile_value', + conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, + ) + response = client.get_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.GetConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, conversation.Conversation) + assert response.name == 'name_value' + assert response.lifecycle_state == conversation.Conversation.LifecycleState.IN_PROGRESS + assert response.conversation_profile == 'conversation_profile_value' + assert response.conversation_stage == conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE + + +def test_get_conversation_from_dict(): + test_get_conversation(request_type=dict) + + +def test_get_conversation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationsClient( + credentials=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_conversation), + '__call__') as call: + client.get_conversation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.GetConversationRequest() + + +@pytest.mark.asyncio +async def test_get_conversation_async(transport: str = 'grpc_asyncio', request_type=conversation.GetConversationRequest): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation( + name='name_value', + lifecycle_state=conversation.Conversation.LifecycleState.IN_PROGRESS, + conversation_profile='conversation_profile_value', + conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, + )) + response = await client.get_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.GetConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, conversation.Conversation) + assert response.name == 'name_value' + assert response.lifecycle_state == conversation.Conversation.LifecycleState.IN_PROGRESS + assert response.conversation_profile == 'conversation_profile_value' + assert response.conversation_stage == conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE + + +@pytest.mark.asyncio +async def test_get_conversation_async_from_dict(): + await test_get_conversation_async(request_type=dict) + + +def test_get_conversation_field_headers(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation.GetConversationRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation), + '__call__') as call: + call.return_value = conversation.Conversation() + client.get_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_conversation_field_headers_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation.GetConversationRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) + await client.get_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_conversation_flattened(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.Conversation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_conversation( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_conversation_flattened_error(): + client = ConversationsClient( + credentials=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_conversation( + conversation.GetConversationRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_conversation_flattened_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.Conversation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_conversation( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_conversation_flattened_error_async(): + client = ConversationsAsyncClient( + credentials=ga_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_conversation( + conversation.GetConversationRequest(), + name='name_value', + ) + + +def test_complete_conversation(transport: str = 'grpc', request_type=conversation.CompleteConversationRequest): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.Conversation( + name='name_value', + lifecycle_state=conversation.Conversation.LifecycleState.IN_PROGRESS, + conversation_profile='conversation_profile_value', + conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, + ) + response = client.complete_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.CompleteConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, conversation.Conversation) + assert response.name == 'name_value' + assert response.lifecycle_state == conversation.Conversation.LifecycleState.IN_PROGRESS + assert response.conversation_profile == 'conversation_profile_value' + assert response.conversation_stage == conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE + + +def test_complete_conversation_from_dict(): + test_complete_conversation(request_type=dict) + + +def test_complete_conversation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_conversation), + '__call__') as call: + client.complete_conversation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.CompleteConversationRequest() + + +@pytest.mark.asyncio +async def test_complete_conversation_async(transport: str = 'grpc_asyncio', request_type=conversation.CompleteConversationRequest): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation( + name='name_value', + lifecycle_state=conversation.Conversation.LifecycleState.IN_PROGRESS, + conversation_profile='conversation_profile_value', + conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, + )) + response = await client.complete_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.CompleteConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, conversation.Conversation) + assert response.name == 'name_value' + assert response.lifecycle_state == conversation.Conversation.LifecycleState.IN_PROGRESS + assert response.conversation_profile == 'conversation_profile_value' + assert response.conversation_stage == conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE + + +@pytest.mark.asyncio +async def test_complete_conversation_async_from_dict(): + await test_complete_conversation_async(request_type=dict) + + +def test_complete_conversation_field_headers(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation.CompleteConversationRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_conversation), + '__call__') as call: + call.return_value = conversation.Conversation() + client.complete_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_complete_conversation_field_headers_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation.CompleteConversationRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_conversation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) + await client.complete_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_complete_conversation_flattened(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.Conversation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.complete_conversation( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_complete_conversation_flattened_error(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.complete_conversation( + conversation.CompleteConversationRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_complete_conversation_flattened_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.Conversation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.complete_conversation( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_complete_conversation_flattened_error_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.complete_conversation( + conversation.CompleteConversationRequest(), + name='name_value', + ) + + +def test_list_messages(transport: str = 'grpc', request_type=conversation.ListMessagesRequest): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_messages), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.ListMessagesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_messages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.ListMessagesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMessagesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_messages_from_dict(): + test_list_messages(request_type=dict) + + +def test_list_messages_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationsClient( + credentials=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_messages), + '__call__') as call: + client.list_messages() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.ListMessagesRequest() + + +@pytest.mark.asyncio +async def test_list_messages_async(transport: str = 'grpc_asyncio', request_type=conversation.ListMessagesRequest): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_messages), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation.ListMessagesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_messages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.ListMessagesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMessagesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_messages_async_from_dict(): + await test_list_messages_async(request_type=dict) + + +def test_list_messages_field_headers(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation.ListMessagesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_messages), + '__call__') as call: + call.return_value = conversation.ListMessagesResponse() + client.list_messages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_messages_field_headers_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation.ListMessagesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_messages), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.ListMessagesResponse()) + await client.list_messages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_messages_flattened(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_messages), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.ListMessagesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_messages( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_messages_flattened_error(): + client = ConversationsClient( + credentials=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_messages( + conversation.ListMessagesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_messages_flattened_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_messages), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.ListMessagesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.ListMessagesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_messages( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_messages_flattened_error_async(): + client = ConversationsAsyncClient( + credentials=ga_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_messages( + conversation.ListMessagesRequest(), + parent='parent_value', + ) + + +def test_list_messages_pager(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_messages), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + conversation.ListMessagesResponse( + messages=[ + participant.Message(), + participant.Message(), + participant.Message(), + ], + next_page_token='abc', + ), + conversation.ListMessagesResponse( + messages=[], + next_page_token='def', + ), + conversation.ListMessagesResponse( + messages=[ + participant.Message(), + ], + next_page_token='ghi', + ), + conversation.ListMessagesResponse( + messages=[ + participant.Message(), + participant.Message(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_messages(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, participant.Message) + for i in results) + +def test_list_messages_pages(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_messages), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + conversation.ListMessagesResponse( + messages=[ + participant.Message(), + participant.Message(), + participant.Message(), + ], + next_page_token='abc', + ), + conversation.ListMessagesResponse( + messages=[], + next_page_token='def', + ), + conversation.ListMessagesResponse( + messages=[ + participant.Message(), + ], + next_page_token='ghi', + ), + conversation.ListMessagesResponse( + messages=[ + participant.Message(), + participant.Message(), + ], + ), + RuntimeError, + ) + pages = list(client.list_messages(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_messages_async_pager(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_messages), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + conversation.ListMessagesResponse( + messages=[ + participant.Message(), + participant.Message(), + participant.Message(), + ], + next_page_token='abc', + ), + conversation.ListMessagesResponse( + messages=[], + next_page_token='def', + ), + conversation.ListMessagesResponse( + messages=[ + participant.Message(), + ], + next_page_token='ghi', + ), + conversation.ListMessagesResponse( + messages=[ + participant.Message(), + participant.Message(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_messages(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, participant.Message) + for i in responses) + +@pytest.mark.asyncio +async def test_list_messages_async_pages(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_messages), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + conversation.ListMessagesResponse( + messages=[ + participant.Message(), + participant.Message(), + participant.Message(), + ], + next_page_token='abc', + ), + conversation.ListMessagesResponse( + messages=[], + next_page_token='def', + ), + conversation.ListMessagesResponse( + messages=[ + participant.Message(), + ], + next_page_token='ghi', + ), + conversation.ListMessagesResponse( + messages=[ + participant.Message(), + participant.Message(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_messages(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.ConversationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ConversationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConversationsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ConversationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConversationsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ConversationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ConversationsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ConversationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ConversationsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ConversationsGrpcTransport, + transports.ConversationsGrpcAsyncIOTransport, +]) +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 = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ConversationsGrpcTransport, + ) + +def test_conversations_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ConversationsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_conversations_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2.services.conversations.transports.ConversationsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ConversationsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_conversation', + 'list_conversations', + 'get_conversation', + 'complete_conversation', + 'list_messages', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_conversations_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.dialogflow_v2.services.conversations.transports.ConversationsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConversationsTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_conversations_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.dialogflow_v2.services.conversations.transports.ConversationsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConversationsTransport() + adc.assert_called_once() + + +def test_conversations_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) + ConversationsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ConversationsGrpcTransport, + transports.ConversationsGrpcAsyncIOTransport, + ], +) +def test_conversations_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationsGrpcTransport, grpc_helpers), + (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_conversations_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ConversationsGrpcTransport, transports.ConversationsGrpcAsyncIOTransport]) +def test_conversations_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_conversations_host_no_port(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_conversations_host_with_port(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_conversations_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ConversationsGrpcTransport( + 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_conversations_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ConversationsGrpcAsyncIOTransport( + 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.ConversationsGrpcTransport, transports.ConversationsGrpcAsyncIOTransport]) +def test_conversations_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.ConversationsGrpcTransport, transports.ConversationsGrpcAsyncIOTransport]) +def test_conversations_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_conversation_path(): + project = "squid" + conversation = "clam" + expected = "projects/{project}/conversations/{conversation}".format(project=project, conversation=conversation, ) + actual = ConversationsClient.conversation_path(project, conversation) + assert expected == actual + + +def test_parse_conversation_path(): + expected = { + "project": "whelk", + "conversation": "octopus", + } + path = ConversationsClient.conversation_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationsClient.parse_conversation_path(path) + assert expected == actual + +def test_conversation_profile_path(): + project = "oyster" + conversation_profile = "nudibranch" + expected = "projects/{project}/conversationProfiles/{conversation_profile}".format(project=project, conversation_profile=conversation_profile, ) + actual = ConversationsClient.conversation_profile_path(project, conversation_profile) + assert expected == actual + + +def test_parse_conversation_profile_path(): + expected = { + "project": "cuttlefish", + "conversation_profile": "mussel", + } + path = ConversationsClient.conversation_profile_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationsClient.parse_conversation_profile_path(path) + assert expected == actual + +def test_message_path(): + project = "winkle" + conversation = "nautilus" + message = "scallop" + expected = "projects/{project}/conversations/{conversation}/messages/{message}".format(project=project, conversation=conversation, message=message, ) + actual = ConversationsClient.message_path(project, conversation, message) + assert expected == actual + + +def test_parse_message_path(): + expected = { + "project": "abalone", + "conversation": "squid", + "message": "clam", + } + path = ConversationsClient.message_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationsClient.parse_message_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ConversationsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = ConversationsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = ConversationsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = ConversationsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ConversationsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = ConversationsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = ConversationsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = ConversationsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationsClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ConversationsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = ConversationsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationsClient.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.ConversationsTransport, '_prep_wrapped_messages') as prep: + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ConversationsTransport, '_prep_wrapped_messages') as prep: + transport_class = ConversationsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_documents.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_documents.py new file mode 100644 index 000000000..cdfd69fd9 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_documents.py @@ -0,0 +1,2751 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.documents import DocumentsAsyncClient +from google.cloud.dialogflow_v2.services.documents import DocumentsClient +from google.cloud.dialogflow_v2.services.documents import pagers +from google.cloud.dialogflow_v2.services.documents import transports +from google.cloud.dialogflow_v2.types import document +from google.cloud.dialogflow_v2.types import document as gcd_document +from google.cloud.dialogflow_v2.types import gcs +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert DocumentsClient._get_default_mtls_endpoint(None) is None + assert DocumentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert DocumentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert DocumentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert DocumentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert DocumentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + DocumentsClient, + DocumentsAsyncClient, +]) +def test_documents_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.DocumentsGrpcTransport, "grpc"), + (transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_documents_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + DocumentsClient, + DocumentsAsyncClient, +]) +def test_documents_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 == 'dialogflow.googleapis.com:443' + + +def test_documents_client_get_transport_class(): + transport = DocumentsClient.get_transport_class() + available_transports = [ + transports.DocumentsGrpcTransport, + ] + assert transport in available_transports + + transport = DocumentsClient.get_transport_class("grpc") + assert transport == transports.DocumentsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DocumentsClient, transports.DocumentsGrpcTransport, "grpc"), + (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(DocumentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentsClient)) +@mock.patch.object(DocumentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentsAsyncClient)) +def test_documents_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(DocumentsClient, '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(DocumentsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (DocumentsClient, transports.DocumentsGrpcTransport, "grpc", "true"), + (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DocumentsClient, transports.DocumentsGrpcTransport, "grpc", "false"), + (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(DocumentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentsClient)) +@mock.patch.object(DocumentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_documents_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DocumentsClient, transports.DocumentsGrpcTransport, "grpc"), + (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_documents_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DocumentsClient, transports.DocumentsGrpcTransport, "grpc"), + (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_documents_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_documents_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2.services.documents.transports.DocumentsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = DocumentsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_documents(transport: str = 'grpc', request_type=document.ListDocumentsRequest): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document.ListDocumentsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document.ListDocumentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDocumentsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_documents_from_dict(): + test_list_documents(request_type=dict) + + +def test_list_documents_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentsClient( + credentials=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_documents), + '__call__') as call: + client.list_documents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document.ListDocumentsRequest() + + +@pytest.mark.asyncio +async def test_list_documents_async(transport: str = 'grpc_asyncio', request_type=document.ListDocumentsRequest): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document.ListDocumentsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document.ListDocumentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDocumentsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_documents_async_from_dict(): + await test_list_documents_async(request_type=dict) + + +def test_list_documents_field_headers(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document.ListDocumentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + call.return_value = document.ListDocumentsResponse() + client.list_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_documents_field_headers_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document.ListDocumentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.ListDocumentsResponse()) + await client.list_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_documents_flattened(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document.ListDocumentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_documents( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_documents_flattened_error(): + client = DocumentsClient( + credentials=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_documents( + document.ListDocumentsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_documents_flattened_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document.ListDocumentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.ListDocumentsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_documents( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_documents_flattened_error_async(): + client = DocumentsAsyncClient( + credentials=ga_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_documents( + document.ListDocumentsRequest(), + parent='parent_value', + ) + + +def test_list_documents_pager(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + document.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + document.Document(), + ], + next_page_token='abc', + ), + document.ListDocumentsResponse( + documents=[], + next_page_token='def', + ), + document.ListDocumentsResponse( + documents=[ + document.Document(), + ], + next_page_token='ghi', + ), + document.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_documents(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, document.Document) + for i in results) + +def test_list_documents_pages(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + document.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + document.Document(), + ], + next_page_token='abc', + ), + document.ListDocumentsResponse( + documents=[], + next_page_token='def', + ), + document.ListDocumentsResponse( + documents=[ + document.Document(), + ], + next_page_token='ghi', + ), + document.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + ], + ), + RuntimeError, + ) + pages = list(client.list_documents(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_documents_async_pager(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + document.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + document.Document(), + ], + next_page_token='abc', + ), + document.ListDocumentsResponse( + documents=[], + next_page_token='def', + ), + document.ListDocumentsResponse( + documents=[ + document.Document(), + ], + next_page_token='ghi', + ), + document.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_documents(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, document.Document) + for i in responses) + +@pytest.mark.asyncio +async def test_list_documents_async_pages(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + document.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + document.Document(), + ], + next_page_token='abc', + ), + document.ListDocumentsResponse( + documents=[], + next_page_token='def', + ), + document.ListDocumentsResponse( + documents=[ + document.Document(), + ], + next_page_token='ghi', + ), + document.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_documents(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_document(transport: str = 'grpc', request_type=document.GetDocumentRequest): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document.Document( + name='name_value', + display_name='display_name_value', + mime_type='mime_type_value', + knowledge_types=[document.Document.KnowledgeType.FAQ], + enable_auto_reload=True, + content_uri='content_uri_value', + ) + response = client.get_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document.GetDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, document.Document) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.mime_type == 'mime_type_value' + assert response.knowledge_types == [document.Document.KnowledgeType.FAQ] + assert response.enable_auto_reload is True + + +def test_get_document_from_dict(): + test_get_document(request_type=dict) + + +def test_get_document_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentsClient( + credentials=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_document), + '__call__') as call: + client.get_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document.GetDocumentRequest() + + +@pytest.mark.asyncio +async def test_get_document_async(transport: str = 'grpc_asyncio', request_type=document.GetDocumentRequest): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document.Document( + name='name_value', + display_name='display_name_value', + mime_type='mime_type_value', + knowledge_types=[document.Document.KnowledgeType.FAQ], + enable_auto_reload=True, + )) + response = await client.get_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document.GetDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, document.Document) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.mime_type == 'mime_type_value' + assert response.knowledge_types == [document.Document.KnowledgeType.FAQ] + assert response.enable_auto_reload is True + + +@pytest.mark.asyncio +async def test_get_document_async_from_dict(): + await test_get_document_async(request_type=dict) + + +def test_get_document_field_headers(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document.GetDocumentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_document), + '__call__') as call: + call.return_value = document.Document() + client.get_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_document_field_headers_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document.GetDocumentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) + await client.get_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_document_flattened(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document.Document() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_document( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_document_flattened_error(): + client = DocumentsClient( + credentials=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_document( + document.GetDocumentRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_document_flattened_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document.Document() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_document( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_document_flattened_error_async(): + client = DocumentsAsyncClient( + credentials=ga_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_document( + document.GetDocumentRequest(), + name='name_value', + ) + + +def test_create_document(transport: str = 'grpc', request_type=gcd_document.CreateDocumentRequest): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_document.CreateDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_document_from_dict(): + test_create_document(request_type=dict) + + +def test_create_document_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentsClient( + credentials=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_document), + '__call__') as call: + client.create_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_document.CreateDocumentRequest() + + +@pytest.mark.asyncio +async def test_create_document_async(transport: str = 'grpc_asyncio', request_type=gcd_document.CreateDocumentRequest): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_document.CreateDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_document_async_from_dict(): + await test_create_document_async(request_type=dict) + + +def test_create_document_field_headers(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_document.CreateDocumentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_document), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_document_field_headers_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_document.CreateDocumentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_document_flattened(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_document( + parent='parent_value', + document=gcd_document.Document(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].document + mock_val = gcd_document.Document(name='name_value') + assert arg == mock_val + + +def test_create_document_flattened_error(): + client = DocumentsClient( + credentials=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_document( + gcd_document.CreateDocumentRequest(), + parent='parent_value', + document=gcd_document.Document(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_document_flattened_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_document( + parent='parent_value', + document=gcd_document.Document(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].document + mock_val = gcd_document.Document(name='name_value') + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_document_flattened_error_async(): + client = DocumentsAsyncClient( + credentials=ga_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_document( + gcd_document.CreateDocumentRequest(), + parent='parent_value', + document=gcd_document.Document(name='name_value'), + ) + + +def test_delete_document(transport: str = 'grpc', request_type=document.DeleteDocumentRequest): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document.DeleteDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_document_from_dict(): + test_delete_document(request_type=dict) + + +def test_delete_document_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentsClient( + credentials=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_document), + '__call__') as call: + client.delete_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document.DeleteDocumentRequest() + + +@pytest.mark.asyncio +async def test_delete_document_async(transport: str = 'grpc_asyncio', request_type=document.DeleteDocumentRequest): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document.DeleteDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_document_async_from_dict(): + await test_delete_document_async(request_type=dict) + + +def test_delete_document_field_headers(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document.DeleteDocumentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_document), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_document_field_headers_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document.DeleteDocumentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_document_flattened(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_document( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_document_flattened_error(): + client = DocumentsClient( + credentials=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_document( + document.DeleteDocumentRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_document_flattened_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_document( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_document_flattened_error_async(): + client = DocumentsAsyncClient( + credentials=ga_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_document( + document.DeleteDocumentRequest(), + name='name_value', + ) + + +def test_update_document(transport: str = 'grpc', request_type=gcd_document.UpdateDocumentRequest): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_document.UpdateDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_document_from_dict(): + test_update_document(request_type=dict) + + +def test_update_document_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentsClient( + credentials=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_document), + '__call__') as call: + client.update_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_document.UpdateDocumentRequest() + + +@pytest.mark.asyncio +async def test_update_document_async(transport: str = 'grpc_asyncio', request_type=gcd_document.UpdateDocumentRequest): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_document.UpdateDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_document_async_from_dict(): + await test_update_document_async(request_type=dict) + + +def test_update_document_field_headers(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_document.UpdateDocumentRequest() + + request.document.name = 'document.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_document), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'document.name=document.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_document_field_headers_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_document.UpdateDocumentRequest() + + request.document.name = 'document.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'document.name=document.name/value', + ) in kw['metadata'] + + +def test_update_document_flattened(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_document( + document=gcd_document.Document(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].document + mock_val = gcd_document.Document(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_document_flattened_error(): + client = DocumentsClient( + credentials=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_document( + gcd_document.UpdateDocumentRequest(), + document=gcd_document.Document(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_document_flattened_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_document( + document=gcd_document.Document(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].document + mock_val = gcd_document.Document(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_document_flattened_error_async(): + client = DocumentsAsyncClient( + credentials=ga_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_document( + gcd_document.UpdateDocumentRequest(), + document=gcd_document.Document(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_reload_document(transport: str = 'grpc', request_type=document.ReloadDocumentRequest): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reload_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.reload_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document.ReloadDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_reload_document_from_dict(): + test_reload_document(request_type=dict) + + +def test_reload_document_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reload_document), + '__call__') as call: + client.reload_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document.ReloadDocumentRequest() + + +@pytest.mark.asyncio +async def test_reload_document_async(transport: str = 'grpc_asyncio', request_type=document.ReloadDocumentRequest): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reload_document), + '__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.reload_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document.ReloadDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_reload_document_async_from_dict(): + await test_reload_document_async(request_type=dict) + + +def test_reload_document_field_headers(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document.ReloadDocumentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reload_document), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.reload_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_reload_document_field_headers_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document.ReloadDocumentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reload_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.reload_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_reload_document_flattened(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reload_document), + '__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.reload_document( + name='name_value', + content_uri='content_uri_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + assert args[0].content_uri == 'content_uri_value' + + +def test_reload_document_flattened_error(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.reload_document( + document.ReloadDocumentRequest(), + name='name_value', + content_uri='content_uri_value', + ) + + +@pytest.mark.asyncio +async def test_reload_document_flattened_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reload_document), + '__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.reload_document( + name='name_value', + content_uri='content_uri_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + assert args[0].content_uri == 'content_uri_value' + + +@pytest.mark.asyncio +async def test_reload_document_flattened_error_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.reload_document( + document.ReloadDocumentRequest(), + name='name_value', + content_uri='content_uri_value', + ) + + +def test_export_document(transport: str = 'grpc', request_type=document.ExportDocumentRequest): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.export_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document.ExportDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_export_document_from_dict(): + test_export_document(request_type=dict) + + +def test_export_document_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_document), + '__call__') as call: + client.export_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document.ExportDocumentRequest() + + +@pytest.mark.asyncio +async def test_export_document_async(transport: str = 'grpc_asyncio', request_type=document.ExportDocumentRequest): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_document), + '__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.export_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document.ExportDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_export_document_async_from_dict(): + await test_export_document_async(request_type=dict) + + +def test_export_document_field_headers(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document.ExportDocumentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_document), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.export_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_export_document_field_headers_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document.ExportDocumentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.export_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DocumentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DocumentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DocumentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DocumentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DocumentsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DocumentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DocumentsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DocumentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DocumentsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.DocumentsGrpcTransport, + transports.DocumentsGrpcAsyncIOTransport, +]) +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 = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DocumentsGrpcTransport, + ) + +def test_documents_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DocumentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_documents_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2.services.documents.transports.DocumentsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.DocumentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_documents', + 'get_document', + 'create_document', + 'delete_document', + 'update_document', + 'reload_document', + 'export_document', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +def test_documents_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.dialogflow_v2.services.documents.transports.DocumentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DocumentsTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_documents_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.dialogflow_v2.services.documents.transports.DocumentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DocumentsTransport() + adc.assert_called_once() + + +def test_documents_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) + DocumentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DocumentsGrpcTransport, + transports.DocumentsGrpcAsyncIOTransport, + ], +) +def test_documents_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DocumentsGrpcTransport, grpc_helpers), + (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_documents_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.DocumentsGrpcTransport, transports.DocumentsGrpcAsyncIOTransport]) +def test_documents_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_documents_host_no_port(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_documents_host_with_port(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_documents_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DocumentsGrpcTransport( + 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_documents_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DocumentsGrpcAsyncIOTransport( + 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.DocumentsGrpcTransport, transports.DocumentsGrpcAsyncIOTransport]) +def test_documents_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.DocumentsGrpcTransport, transports.DocumentsGrpcAsyncIOTransport]) +def test_documents_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_documents_grpc_lro_client(): + client = DocumentsClient( + 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_documents_grpc_lro_async_client(): + client = DocumentsAsyncClient( + 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_document_path(): + project = "squid" + knowledge_base = "clam" + document = "whelk" + expected = "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format(project=project, knowledge_base=knowledge_base, document=document, ) + actual = DocumentsClient.document_path(project, knowledge_base, document) + assert expected == actual + + +def test_parse_document_path(): + expected = { + "project": "octopus", + "knowledge_base": "oyster", + "document": "nudibranch", + } + path = DocumentsClient.document_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentsClient.parse_document_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = DocumentsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = DocumentsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = DocumentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = DocumentsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DocumentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = DocumentsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = DocumentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = DocumentsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentsClient.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 = DocumentsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = DocumentsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentsClient.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.DocumentsTransport, '_prep_wrapped_messages') as prep: + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.DocumentsTransport, '_prep_wrapped_messages') as prep: + transport_class = DocumentsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_entity_types.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_entity_types.py new file mode 100644 index 000000000..e87c788ff --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_entity_types.py @@ -0,0 +1,3573 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.entity_types import EntityTypesAsyncClient +from google.cloud.dialogflow_v2.services.entity_types import EntityTypesClient +from google.cloud.dialogflow_v2.services.entity_types import pagers +from google.cloud.dialogflow_v2.services.entity_types import transports +from google.cloud.dialogflow_v2.types import entity_type +from google.cloud.dialogflow_v2.types import entity_type as gcd_entity_type +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 struct_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert EntityTypesClient._get_default_mtls_endpoint(None) is None + assert EntityTypesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert EntityTypesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert EntityTypesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert EntityTypesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert EntityTypesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + EntityTypesClient, + EntityTypesAsyncClient, +]) +def test_entity_types_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.EntityTypesGrpcTransport, "grpc"), + (transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_entity_types_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + EntityTypesClient, + EntityTypesAsyncClient, +]) +def test_entity_types_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 == 'dialogflow.googleapis.com:443' + + +def test_entity_types_client_get_transport_class(): + transport = EntityTypesClient.get_transport_class() + available_transports = [ + transports.EntityTypesGrpcTransport, + ] + assert transport in available_transports + + transport = EntityTypesClient.get_transport_class("grpc") + assert transport == transports.EntityTypesGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc"), + (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(EntityTypesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EntityTypesClient)) +@mock.patch.object(EntityTypesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EntityTypesAsyncClient)) +def test_entity_types_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(EntityTypesClient, '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(EntityTypesClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc", "true"), + (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc", "false"), + (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(EntityTypesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EntityTypesClient)) +@mock.patch.object(EntityTypesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EntityTypesAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_entity_types_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc"), + (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_entity_types_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc"), + (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_entity_types_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_entity_types_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2.services.entity_types.transports.EntityTypesGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = EntityTypesClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_entity_types(transport: str = 'grpc', request_type=entity_type.ListEntityTypesRequest): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = entity_type.ListEntityTypesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.ListEntityTypesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEntityTypesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_entity_types_from_dict(): + test_list_entity_types(request_type=dict) + + +def test_list_entity_types_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EntityTypesClient( + credentials=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_entity_types), + '__call__') as call: + client.list_entity_types() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.ListEntityTypesRequest() + + +@pytest.mark.asyncio +async def test_list_entity_types_async(transport: str = 'grpc_asyncio', request_type=entity_type.ListEntityTypesRequest): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(entity_type.ListEntityTypesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.ListEntityTypesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEntityTypesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_entity_types_async_from_dict(): + await test_list_entity_types_async(request_type=dict) + + +def test_list_entity_types_field_headers(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.ListEntityTypesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entity_types), + '__call__') as call: + call.return_value = entity_type.ListEntityTypesResponse() + client.list_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_entity_types_field_headers_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.ListEntityTypesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entity_types), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(entity_type.ListEntityTypesResponse()) + await client.list_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_entity_types_flattened(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = entity_type.ListEntityTypesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_entity_types( + parent='parent_value', + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +def test_list_entity_types_flattened_error(): + client = EntityTypesClient( + credentials=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_entity_types( + entity_type.ListEntityTypesRequest(), + parent='parent_value', + language_code='language_code_value', + ) + + +@pytest.mark.asyncio +async def test_list_entity_types_flattened_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = entity_type.ListEntityTypesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(entity_type.ListEntityTypesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_entity_types( + parent='parent_value', + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_entity_types_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=ga_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_entity_types( + entity_type.ListEntityTypesRequest(), + parent='parent_value', + language_code='language_code_value', + ) + + +def test_list_entity_types_pager(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entity_types), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + entity_type.ListEntityTypesResponse( + entity_types=[ + entity_type.EntityType(), + entity_type.EntityType(), + entity_type.EntityType(), + ], + next_page_token='abc', + ), + entity_type.ListEntityTypesResponse( + entity_types=[], + next_page_token='def', + ), + entity_type.ListEntityTypesResponse( + entity_types=[ + entity_type.EntityType(), + ], + next_page_token='ghi', + ), + entity_type.ListEntityTypesResponse( + entity_types=[ + entity_type.EntityType(), + entity_type.EntityType(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_entity_types(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, entity_type.EntityType) + for i in results) + +def test_list_entity_types_pages(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entity_types), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + entity_type.ListEntityTypesResponse( + entity_types=[ + entity_type.EntityType(), + entity_type.EntityType(), + entity_type.EntityType(), + ], + next_page_token='abc', + ), + entity_type.ListEntityTypesResponse( + entity_types=[], + next_page_token='def', + ), + entity_type.ListEntityTypesResponse( + entity_types=[ + entity_type.EntityType(), + ], + next_page_token='ghi', + ), + entity_type.ListEntityTypesResponse( + entity_types=[ + entity_type.EntityType(), + entity_type.EntityType(), + ], + ), + RuntimeError, + ) + pages = list(client.list_entity_types(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_entity_types_async_pager(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entity_types), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + entity_type.ListEntityTypesResponse( + entity_types=[ + entity_type.EntityType(), + entity_type.EntityType(), + entity_type.EntityType(), + ], + next_page_token='abc', + ), + entity_type.ListEntityTypesResponse( + entity_types=[], + next_page_token='def', + ), + entity_type.ListEntityTypesResponse( + entity_types=[ + entity_type.EntityType(), + ], + next_page_token='ghi', + ), + entity_type.ListEntityTypesResponse( + entity_types=[ + entity_type.EntityType(), + entity_type.EntityType(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_entity_types(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, entity_type.EntityType) + for i in responses) + +@pytest.mark.asyncio +async def test_list_entity_types_async_pages(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entity_types), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + entity_type.ListEntityTypesResponse( + entity_types=[ + entity_type.EntityType(), + entity_type.EntityType(), + entity_type.EntityType(), + ], + next_page_token='abc', + ), + entity_type.ListEntityTypesResponse( + entity_types=[], + next_page_token='def', + ), + entity_type.ListEntityTypesResponse( + entity_types=[ + entity_type.EntityType(), + ], + next_page_token='ghi', + ), + entity_type.ListEntityTypesResponse( + entity_types=[ + entity_type.EntityType(), + entity_type.EntityType(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_entity_types(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_entity_type(transport: str = 'grpc', request_type=entity_type.GetEntityTypeRequest): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = entity_type.EntityType( + name='name_value', + display_name='display_name_value', + kind=entity_type.EntityType.Kind.KIND_MAP, + auto_expansion_mode=entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, + enable_fuzzy_extraction=True, + ) + response = client.get_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.GetEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, entity_type.EntityType) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.kind == entity_type.EntityType.Kind.KIND_MAP + assert response.auto_expansion_mode == entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT + assert response.enable_fuzzy_extraction is True + + +def test_get_entity_type_from_dict(): + test_get_entity_type(request_type=dict) + + +def test_get_entity_type_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EntityTypesClient( + credentials=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_entity_type), + '__call__') as call: + client.get_entity_type() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.GetEntityTypeRequest() + + +@pytest.mark.asyncio +async def test_get_entity_type_async(transport: str = 'grpc_asyncio', request_type=entity_type.GetEntityTypeRequest): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(entity_type.EntityType( + name='name_value', + display_name='display_name_value', + kind=entity_type.EntityType.Kind.KIND_MAP, + auto_expansion_mode=entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, + enable_fuzzy_extraction=True, + )) + response = await client.get_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.GetEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, entity_type.EntityType) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.kind == entity_type.EntityType.Kind.KIND_MAP + assert response.auto_expansion_mode == entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT + assert response.enable_fuzzy_extraction is True + + +@pytest.mark.asyncio +async def test_get_entity_type_async_from_dict(): + await test_get_entity_type_async(request_type=dict) + + +def test_get_entity_type_field_headers(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.GetEntityTypeRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_entity_type), + '__call__') as call: + call.return_value = entity_type.EntityType() + client.get_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_entity_type_field_headers_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.GetEntityTypeRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_entity_type), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(entity_type.EntityType()) + await client.get_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_entity_type_flattened(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = entity_type.EntityType() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_entity_type( + name='name_value', + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +def test_get_entity_type_flattened_error(): + client = EntityTypesClient( + credentials=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_entity_type( + entity_type.GetEntityTypeRequest(), + name='name_value', + language_code='language_code_value', + ) + + +@pytest.mark.asyncio +async def test_get_entity_type_flattened_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = entity_type.EntityType() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(entity_type.EntityType()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_entity_type( + name='name_value', + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_entity_type_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=ga_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_entity_type( + entity_type.GetEntityTypeRequest(), + name='name_value', + language_code='language_code_value', + ) + + +def test_create_entity_type(transport: str = 'grpc', request_type=gcd_entity_type.CreateEntityTypeRequest): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_entity_type.EntityType( + name='name_value', + display_name='display_name_value', + kind=gcd_entity_type.EntityType.Kind.KIND_MAP, + auto_expansion_mode=gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, + enable_fuzzy_extraction=True, + ) + response = client.create_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_entity_type.CreateEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_entity_type.EntityType) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.kind == gcd_entity_type.EntityType.Kind.KIND_MAP + assert response.auto_expansion_mode == gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT + assert response.enable_fuzzy_extraction is True + + +def test_create_entity_type_from_dict(): + test_create_entity_type(request_type=dict) + + +def test_create_entity_type_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EntityTypesClient( + credentials=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_entity_type), + '__call__') as call: + client.create_entity_type() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_entity_type.CreateEntityTypeRequest() + + +@pytest.mark.asyncio +async def test_create_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcd_entity_type.CreateEntityTypeRequest): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_entity_type.EntityType( + name='name_value', + display_name='display_name_value', + kind=gcd_entity_type.EntityType.Kind.KIND_MAP, + auto_expansion_mode=gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, + enable_fuzzy_extraction=True, + )) + response = await client.create_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_entity_type.CreateEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_entity_type.EntityType) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.kind == gcd_entity_type.EntityType.Kind.KIND_MAP + assert response.auto_expansion_mode == gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT + assert response.enable_fuzzy_extraction is True + + +@pytest.mark.asyncio +async def test_create_entity_type_async_from_dict(): + await test_create_entity_type_async(request_type=dict) + + +def test_create_entity_type_field_headers(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_entity_type.CreateEntityTypeRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_entity_type), + '__call__') as call: + call.return_value = gcd_entity_type.EntityType() + client.create_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_entity_type_field_headers_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_entity_type.CreateEntityTypeRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_entity_type), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_entity_type.EntityType()) + await client.create_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_entity_type_flattened(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_entity_type.EntityType() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_entity_type( + parent='parent_value', + entity_type=gcd_entity_type.EntityType(name='name_value'), + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].entity_type + mock_val = gcd_entity_type.EntityType(name='name_value') + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +def test_create_entity_type_flattened_error(): + client = EntityTypesClient( + credentials=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_entity_type( + gcd_entity_type.CreateEntityTypeRequest(), + parent='parent_value', + entity_type=gcd_entity_type.EntityType(name='name_value'), + language_code='language_code_value', + ) + + +@pytest.mark.asyncio +async def test_create_entity_type_flattened_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_entity_type.EntityType() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_entity_type.EntityType()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_entity_type( + parent='parent_value', + entity_type=gcd_entity_type.EntityType(name='name_value'), + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].entity_type + mock_val = gcd_entity_type.EntityType(name='name_value') + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_entity_type_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=ga_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_entity_type( + gcd_entity_type.CreateEntityTypeRequest(), + parent='parent_value', + entity_type=gcd_entity_type.EntityType(name='name_value'), + language_code='language_code_value', + ) + + +def test_update_entity_type(transport: str = 'grpc', request_type=gcd_entity_type.UpdateEntityTypeRequest): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_entity_type.EntityType( + name='name_value', + display_name='display_name_value', + kind=gcd_entity_type.EntityType.Kind.KIND_MAP, + auto_expansion_mode=gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, + enable_fuzzy_extraction=True, + ) + response = client.update_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_entity_type.UpdateEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_entity_type.EntityType) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.kind == gcd_entity_type.EntityType.Kind.KIND_MAP + assert response.auto_expansion_mode == gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT + assert response.enable_fuzzy_extraction is True + + +def test_update_entity_type_from_dict(): + test_update_entity_type(request_type=dict) + + +def test_update_entity_type_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EntityTypesClient( + credentials=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_entity_type), + '__call__') as call: + client.update_entity_type() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_entity_type.UpdateEntityTypeRequest() + + +@pytest.mark.asyncio +async def test_update_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcd_entity_type.UpdateEntityTypeRequest): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_entity_type.EntityType( + name='name_value', + display_name='display_name_value', + kind=gcd_entity_type.EntityType.Kind.KIND_MAP, + auto_expansion_mode=gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, + enable_fuzzy_extraction=True, + )) + response = await client.update_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_entity_type.UpdateEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_entity_type.EntityType) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.kind == gcd_entity_type.EntityType.Kind.KIND_MAP + assert response.auto_expansion_mode == gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT + assert response.enable_fuzzy_extraction is True + + +@pytest.mark.asyncio +async def test_update_entity_type_async_from_dict(): + await test_update_entity_type_async(request_type=dict) + + +def test_update_entity_type_field_headers(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_entity_type.UpdateEntityTypeRequest() + + request.entity_type.name = 'entity_type.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_entity_type), + '__call__') as call: + call.return_value = gcd_entity_type.EntityType() + client.update_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'entity_type.name=entity_type.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_entity_type_field_headers_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_entity_type.UpdateEntityTypeRequest() + + request.entity_type.name = 'entity_type.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_entity_type), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_entity_type.EntityType()) + await client.update_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'entity_type.name=entity_type.name/value', + ) in kw['metadata'] + + +def test_update_entity_type_flattened(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_entity_type.EntityType() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_entity_type( + entity_type=gcd_entity_type.EntityType(name='name_value'), + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].entity_type + mock_val = gcd_entity_type.EntityType(name='name_value') + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +def test_update_entity_type_flattened_error(): + client = EntityTypesClient( + credentials=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_entity_type( + gcd_entity_type.UpdateEntityTypeRequest(), + entity_type=gcd_entity_type.EntityType(name='name_value'), + language_code='language_code_value', + ) + + +@pytest.mark.asyncio +async def test_update_entity_type_flattened_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_entity_type.EntityType() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_entity_type.EntityType()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_entity_type( + entity_type=gcd_entity_type.EntityType(name='name_value'), + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].entity_type + mock_val = gcd_entity_type.EntityType(name='name_value') + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_entity_type_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=ga_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_entity_type( + gcd_entity_type.UpdateEntityTypeRequest(), + entity_type=gcd_entity_type.EntityType(name='name_value'), + language_code='language_code_value', + ) + + +def test_delete_entity_type(transport: str = 'grpc', request_type=entity_type.DeleteEntityTypeRequest): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.DeleteEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_entity_type_from_dict(): + test_delete_entity_type(request_type=dict) + + +def test_delete_entity_type_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EntityTypesClient( + credentials=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_entity_type), + '__call__') as call: + client.delete_entity_type() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.DeleteEntityTypeRequest() + + +@pytest.mark.asyncio +async def test_delete_entity_type_async(transport: str = 'grpc_asyncio', request_type=entity_type.DeleteEntityTypeRequest): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.DeleteEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_entity_type_async_from_dict(): + await test_delete_entity_type_async(request_type=dict) + + +def test_delete_entity_type_field_headers(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.DeleteEntityTypeRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_entity_type), + '__call__') as call: + call.return_value = None + client.delete_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_entity_type_field_headers_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.DeleteEntityTypeRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_entity_type), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_entity_type_flattened(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_entity_type), + '__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_entity_type( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_entity_type_flattened_error(): + client = EntityTypesClient( + credentials=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_entity_type( + entity_type.DeleteEntityTypeRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_entity_type_flattened_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_entity_type), + '__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_entity_type( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_entity_type_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=ga_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_entity_type( + entity_type.DeleteEntityTypeRequest(), + name='name_value', + ) + + +def test_batch_update_entity_types(transport: str = 'grpc', request_type=entity_type.BatchUpdateEntityTypesRequest): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.batch_update_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchUpdateEntityTypesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_update_entity_types_from_dict(): + test_batch_update_entity_types(request_type=dict) + + +def test_batch_update_entity_types_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_entity_types), + '__call__') as call: + client.batch_update_entity_types() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchUpdateEntityTypesRequest() + + +@pytest.mark.asyncio +async def test_batch_update_entity_types_async(transport: str = 'grpc_asyncio', request_type=entity_type.BatchUpdateEntityTypesRequest): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.batch_update_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchUpdateEntityTypesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_update_entity_types_async_from_dict(): + await test_batch_update_entity_types_async(request_type=dict) + + +def test_batch_update_entity_types_field_headers(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.BatchUpdateEntityTypesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_entity_types), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.batch_update_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_batch_update_entity_types_field_headers_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.BatchUpdateEntityTypesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_entity_types), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.batch_update_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_batch_delete_entity_types(transport: str = 'grpc', request_type=entity_type.BatchDeleteEntityTypesRequest): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.batch_delete_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchDeleteEntityTypesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_delete_entity_types_from_dict(): + test_batch_delete_entity_types(request_type=dict) + + +def test_batch_delete_entity_types_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entity_types), + '__call__') as call: + client.batch_delete_entity_types() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchDeleteEntityTypesRequest() + + +@pytest.mark.asyncio +async def test_batch_delete_entity_types_async(transport: str = 'grpc_asyncio', request_type=entity_type.BatchDeleteEntityTypesRequest): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.batch_delete_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchDeleteEntityTypesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_delete_entity_types_async_from_dict(): + await test_batch_delete_entity_types_async(request_type=dict) + + +def test_batch_delete_entity_types_field_headers(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.BatchDeleteEntityTypesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entity_types), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.batch_delete_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_batch_delete_entity_types_field_headers_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.BatchDeleteEntityTypesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entity_types), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.batch_delete_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_batch_delete_entity_types_flattened(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_delete_entity_types( + parent='parent_value', + entity_type_names=['entity_type_names_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].entity_type_names + mock_val = ['entity_type_names_value'] + assert arg == mock_val + + +def test_batch_delete_entity_types_flattened_error(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_delete_entity_types( + entity_type.BatchDeleteEntityTypesRequest(), + parent='parent_value', + entity_type_names=['entity_type_names_value'], + ) + + +@pytest.mark.asyncio +async def test_batch_delete_entity_types_flattened_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_delete_entity_types( + parent='parent_value', + entity_type_names=['entity_type_names_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].entity_type_names + mock_val = ['entity_type_names_value'] + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_batch_delete_entity_types_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_delete_entity_types( + entity_type.BatchDeleteEntityTypesRequest(), + parent='parent_value', + entity_type_names=['entity_type_names_value'], + ) + + +def test_batch_create_entities(transport: str = 'grpc', request_type=entity_type.BatchCreateEntitiesRequest): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_entities), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.batch_create_entities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchCreateEntitiesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_create_entities_from_dict(): + test_batch_create_entities(request_type=dict) + + +def test_batch_create_entities_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_entities), + '__call__') as call: + client.batch_create_entities() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchCreateEntitiesRequest() + + +@pytest.mark.asyncio +async def test_batch_create_entities_async(transport: str = 'grpc_asyncio', request_type=entity_type.BatchCreateEntitiesRequest): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_entities), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.batch_create_entities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchCreateEntitiesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_create_entities_async_from_dict(): + await test_batch_create_entities_async(request_type=dict) + + +def test_batch_create_entities_field_headers(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.BatchCreateEntitiesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_entities), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.batch_create_entities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_batch_create_entities_field_headers_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.BatchCreateEntitiesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_entities), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.batch_create_entities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_batch_create_entities_flattened(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_entities), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_create_entities( + parent='parent_value', + entities=[entity_type.EntityType.Entity(value='value_value')], + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].entities + mock_val = [entity_type.EntityType.Entity(value='value_value')] + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +def test_batch_create_entities_flattened_error(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_create_entities( + entity_type.BatchCreateEntitiesRequest(), + parent='parent_value', + entities=[entity_type.EntityType.Entity(value='value_value')], + language_code='language_code_value', + ) + + +@pytest.mark.asyncio +async def test_batch_create_entities_flattened_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_entities), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_create_entities( + parent='parent_value', + entities=[entity_type.EntityType.Entity(value='value_value')], + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].entities + mock_val = [entity_type.EntityType.Entity(value='value_value')] + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_batch_create_entities_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_create_entities( + entity_type.BatchCreateEntitiesRequest(), + parent='parent_value', + entities=[entity_type.EntityType.Entity(value='value_value')], + language_code='language_code_value', + ) + + +def test_batch_update_entities(transport: str = 'grpc', request_type=entity_type.BatchUpdateEntitiesRequest): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_entities), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.batch_update_entities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchUpdateEntitiesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_update_entities_from_dict(): + test_batch_update_entities(request_type=dict) + + +def test_batch_update_entities_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_entities), + '__call__') as call: + client.batch_update_entities() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchUpdateEntitiesRequest() + + +@pytest.mark.asyncio +async def test_batch_update_entities_async(transport: str = 'grpc_asyncio', request_type=entity_type.BatchUpdateEntitiesRequest): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_entities), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.batch_update_entities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchUpdateEntitiesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_update_entities_async_from_dict(): + await test_batch_update_entities_async(request_type=dict) + + +def test_batch_update_entities_field_headers(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.BatchUpdateEntitiesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_entities), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.batch_update_entities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_batch_update_entities_field_headers_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.BatchUpdateEntitiesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_entities), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.batch_update_entities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_batch_update_entities_flattened(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_entities), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_update_entities( + parent='parent_value', + entities=[entity_type.EntityType.Entity(value='value_value')], + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].entities + mock_val = [entity_type.EntityType.Entity(value='value_value')] + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +def test_batch_update_entities_flattened_error(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_update_entities( + entity_type.BatchUpdateEntitiesRequest(), + parent='parent_value', + entities=[entity_type.EntityType.Entity(value='value_value')], + language_code='language_code_value', + ) + + +@pytest.mark.asyncio +async def test_batch_update_entities_flattened_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_entities), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_update_entities( + parent='parent_value', + entities=[entity_type.EntityType.Entity(value='value_value')], + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].entities + mock_val = [entity_type.EntityType.Entity(value='value_value')] + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_batch_update_entities_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_update_entities( + entity_type.BatchUpdateEntitiesRequest(), + parent='parent_value', + entities=[entity_type.EntityType.Entity(value='value_value')], + language_code='language_code_value', + ) + + +def test_batch_delete_entities(transport: str = 'grpc', request_type=entity_type.BatchDeleteEntitiesRequest): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entities), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.batch_delete_entities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchDeleteEntitiesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_delete_entities_from_dict(): + test_batch_delete_entities(request_type=dict) + + +def test_batch_delete_entities_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entities), + '__call__') as call: + client.batch_delete_entities() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchDeleteEntitiesRequest() + + +@pytest.mark.asyncio +async def test_batch_delete_entities_async(transport: str = 'grpc_asyncio', request_type=entity_type.BatchDeleteEntitiesRequest): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entities), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.batch_delete_entities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchDeleteEntitiesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_delete_entities_async_from_dict(): + await test_batch_delete_entities_async(request_type=dict) + + +def test_batch_delete_entities_field_headers(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.BatchDeleteEntitiesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entities), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.batch_delete_entities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_batch_delete_entities_field_headers_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.BatchDeleteEntitiesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entities), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.batch_delete_entities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_batch_delete_entities_flattened(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entities), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_delete_entities( + parent='parent_value', + entity_values=['entity_values_value'], + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].entity_values + mock_val = ['entity_values_value'] + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +def test_batch_delete_entities_flattened_error(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_delete_entities( + entity_type.BatchDeleteEntitiesRequest(), + parent='parent_value', + entity_values=['entity_values_value'], + language_code='language_code_value', + ) + + +@pytest.mark.asyncio +async def test_batch_delete_entities_flattened_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entities), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_delete_entities( + parent='parent_value', + entity_values=['entity_values_value'], + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].entity_values + mock_val = ['entity_values_value'] + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_batch_delete_entities_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_delete_entities( + entity_type.BatchDeleteEntitiesRequest(), + parent='parent_value', + entity_values=['entity_values_value'], + language_code='language_code_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.EntityTypesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.EntityTypesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EntityTypesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.EntityTypesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EntityTypesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.EntityTypesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = EntityTypesClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.EntityTypesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.EntityTypesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.EntityTypesGrpcTransport, + transports.EntityTypesGrpcAsyncIOTransport, +]) +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 = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.EntityTypesGrpcTransport, + ) + +def test_entity_types_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.EntityTypesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_entity_types_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2.services.entity_types.transports.EntityTypesTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.EntityTypesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_entity_types', + 'get_entity_type', + 'create_entity_type', + 'update_entity_type', + 'delete_entity_type', + 'batch_update_entity_types', + 'batch_delete_entity_types', + 'batch_create_entities', + 'batch_update_entities', + 'batch_delete_entities', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +def test_entity_types_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.dialogflow_v2.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EntityTypesTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_entity_types_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.dialogflow_v2.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EntityTypesTransport() + adc.assert_called_once() + + +def test_entity_types_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) + EntityTypesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EntityTypesGrpcTransport, + transports.EntityTypesGrpcAsyncIOTransport, + ], +) +def test_entity_types_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EntityTypesGrpcTransport, grpc_helpers), + (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_entity_types_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport]) +def test_entity_types_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_entity_types_host_no_port(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_entity_types_host_with_port(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_entity_types_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EntityTypesGrpcTransport( + 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_entity_types_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EntityTypesGrpcAsyncIOTransport( + 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.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport]) +def test_entity_types_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.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport]) +def test_entity_types_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_entity_types_grpc_lro_client(): + client = EntityTypesClient( + 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_entity_types_grpc_lro_async_client(): + client = EntityTypesAsyncClient( + 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_entity_type_path(): + project = "squid" + entity_type = "clam" + expected = "projects/{project}/agent/entityTypes/{entity_type}".format(project=project, entity_type=entity_type, ) + actual = EntityTypesClient.entity_type_path(project, entity_type) + assert expected == actual + + +def test_parse_entity_type_path(): + expected = { + "project": "whelk", + "entity_type": "octopus", + } + path = EntityTypesClient.entity_type_path(**expected) + + # Check that the path construction is reversible. + actual = EntityTypesClient.parse_entity_type_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = EntityTypesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = EntityTypesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = EntityTypesClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = EntityTypesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = EntityTypesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = EntityTypesClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = EntityTypesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = EntityTypesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = EntityTypesClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = EntityTypesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = EntityTypesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = EntityTypesClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = EntityTypesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = EntityTypesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = EntityTypesClient.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.EntityTypesTransport, '_prep_wrapped_messages') as prep: + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.EntityTypesTransport, '_prep_wrapped_messages') as prep: + transport_class = EntityTypesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_environments.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_environments.py new file mode 100644 index 000000000..5d9c106a4 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_environments.py @@ -0,0 +1,2358 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.environments import EnvironmentsAsyncClient +from google.cloud.dialogflow_v2.services.environments import EnvironmentsClient +from google.cloud.dialogflow_v2.services.environments import pagers +from google.cloud.dialogflow_v2.services.environments import transports +from google.cloud.dialogflow_v2.types import audio_config +from google.cloud.dialogflow_v2.types import environment +from google.cloud.dialogflow_v2.types import fulfillment +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert EnvironmentsClient._get_default_mtls_endpoint(None) is None + assert EnvironmentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert EnvironmentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert EnvironmentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert EnvironmentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert EnvironmentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + EnvironmentsClient, + EnvironmentsAsyncClient, +]) +def test_environments_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.EnvironmentsGrpcTransport, "grpc"), + (transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_environments_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + EnvironmentsClient, + EnvironmentsAsyncClient, +]) +def test_environments_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 == 'dialogflow.googleapis.com:443' + + +def test_environments_client_get_transport_class(): + transport = EnvironmentsClient.get_transport_class() + available_transports = [ + transports.EnvironmentsGrpcTransport, + ] + assert transport in available_transports + + transport = EnvironmentsClient.get_transport_class("grpc") + assert transport == transports.EnvironmentsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(EnvironmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsClient)) +@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsAsyncClient)) +def test_environments_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(EnvironmentsClient, '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(EnvironmentsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", "true"), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", "false"), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(EnvironmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsClient)) +@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_environments_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_environments_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_environments_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_environments_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2.services.environments.transports.EnvironmentsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = EnvironmentsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_environments(transport: str = 'grpc', request_type=environment.ListEnvironmentsRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_environments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.ListEnvironmentsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_environments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.ListEnvironmentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEnvironmentsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_environments_from_dict(): + test_list_environments(request_type=dict) + + +def test_list_environments_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=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_environments), + '__call__') as call: + client.list_environments() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.ListEnvironmentsRequest() + + +@pytest.mark.asyncio +async def test_list_environments_async(transport: str = 'grpc_asyncio', request_type=environment.ListEnvironmentsRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_environments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.ListEnvironmentsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_environments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.ListEnvironmentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEnvironmentsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_environments_async_from_dict(): + await test_list_environments_async(request_type=dict) + + +def test_list_environments_field_headers(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.ListEnvironmentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + call.return_value = environment.ListEnvironmentsResponse() + client.list_environments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_environments_field_headers_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.ListEnvironmentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.ListEnvironmentsResponse()) + await client.list_environments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_environments_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.ListEnvironmentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_environments( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_environments_flattened_error(): + client = EnvironmentsClient( + credentials=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_environments( + environment.ListEnvironmentsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_environments_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.ListEnvironmentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.ListEnvironmentsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_environments( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_environments_flattened_error_async(): + client = EnvironmentsAsyncClient( + credentials=ga_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_environments( + environment.ListEnvironmentsRequest(), + parent='parent_value', + ) + + +def test_list_environments_pager(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.ListEnvironmentsResponse( + environments=[ + environment.Environment(), + environment.Environment(), + environment.Environment(), + ], + next_page_token='abc', + ), + environment.ListEnvironmentsResponse( + environments=[], + next_page_token='def', + ), + environment.ListEnvironmentsResponse( + environments=[ + environment.Environment(), + ], + next_page_token='ghi', + ), + environment.ListEnvironmentsResponse( + environments=[ + environment.Environment(), + environment.Environment(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_environments(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, environment.Environment) + for i in results) + +def test_list_environments_pages(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.ListEnvironmentsResponse( + environments=[ + environment.Environment(), + environment.Environment(), + environment.Environment(), + ], + next_page_token='abc', + ), + environment.ListEnvironmentsResponse( + environments=[], + next_page_token='def', + ), + environment.ListEnvironmentsResponse( + environments=[ + environment.Environment(), + ], + next_page_token='ghi', + ), + environment.ListEnvironmentsResponse( + environments=[ + environment.Environment(), + environment.Environment(), + ], + ), + RuntimeError, + ) + pages = list(client.list_environments(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_environments_async_pager(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.ListEnvironmentsResponse( + environments=[ + environment.Environment(), + environment.Environment(), + environment.Environment(), + ], + next_page_token='abc', + ), + environment.ListEnvironmentsResponse( + environments=[], + next_page_token='def', + ), + environment.ListEnvironmentsResponse( + environments=[ + environment.Environment(), + ], + next_page_token='ghi', + ), + environment.ListEnvironmentsResponse( + environments=[ + environment.Environment(), + environment.Environment(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_environments(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, environment.Environment) + for i in responses) + +@pytest.mark.asyncio +async def test_list_environments_async_pages(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.ListEnvironmentsResponse( + environments=[ + environment.Environment(), + environment.Environment(), + environment.Environment(), + ], + next_page_token='abc', + ), + environment.ListEnvironmentsResponse( + environments=[], + next_page_token='def', + ), + environment.ListEnvironmentsResponse( + environments=[ + environment.Environment(), + ], + next_page_token='ghi', + ), + environment.ListEnvironmentsResponse( + environments=[ + environment.Environment(), + environment.Environment(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_environments(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_environment(transport: str = 'grpc', request_type=environment.GetEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.Environment( + name='name_value', + description='description_value', + agent_version='agent_version_value', + state=environment.Environment.State.STOPPED, + ) + response = client.get_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.agent_version == 'agent_version_value' + assert response.state == environment.Environment.State.STOPPED + + +def test_get_environment_from_dict(): + test_get_environment(request_type=dict) + + +def test_get_environment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=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_environment), + '__call__') as call: + client.get_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_get_environment_async(transport: str = 'grpc_asyncio', request_type=environment.GetEnvironmentRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment( + name='name_value', + description='description_value', + agent_version='agent_version_value', + state=environment.Environment.State.STOPPED, + )) + response = await client.get_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.agent_version == 'agent_version_value' + assert response.state == environment.Environment.State.STOPPED + + +@pytest.mark.asyncio +async def test_get_environment_async_from_dict(): + await test_get_environment_async(request_type=dict) + + +def test_get_environment_field_headers(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.GetEnvironmentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment), + '__call__') as call: + call.return_value = environment.Environment() + client.get_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_environment_field_headers_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.GetEnvironmentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment()) + await client.get_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_create_environment(transport: str = 'grpc', request_type=environment.CreateEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.Environment( + name='name_value', + description='description_value', + agent_version='agent_version_value', + state=environment.Environment.State.STOPPED, + ) + response = client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.CreateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.agent_version == 'agent_version_value' + assert response.state == environment.Environment.State.STOPPED + + +def test_create_environment_from_dict(): + test_create_environment(request_type=dict) + + +def test_create_environment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=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_environment), + '__call__') as call: + client.create_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.CreateEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_create_environment_async(transport: str = 'grpc_asyncio', request_type=environment.CreateEnvironmentRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment( + name='name_value', + description='description_value', + agent_version='agent_version_value', + state=environment.Environment.State.STOPPED, + )) + response = await client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.CreateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.agent_version == 'agent_version_value' + assert response.state == environment.Environment.State.STOPPED + + +@pytest.mark.asyncio +async def test_create_environment_async_from_dict(): + await test_create_environment_async(request_type=dict) + + +def test_create_environment_field_headers(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.CreateEnvironmentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__call__') as call: + call.return_value = environment.Environment() + client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_environment_field_headers_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.CreateEnvironmentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment()) + await client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_update_environment(transport: str = 'grpc', request_type=environment.UpdateEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.Environment( + name='name_value', + description='description_value', + agent_version='agent_version_value', + state=environment.Environment.State.STOPPED, + ) + response = client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.UpdateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.agent_version == 'agent_version_value' + assert response.state == environment.Environment.State.STOPPED + + +def test_update_environment_from_dict(): + test_update_environment(request_type=dict) + + +def test_update_environment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=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_environment), + '__call__') as call: + client.update_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.UpdateEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_update_environment_async(transport: str = 'grpc_asyncio', request_type=environment.UpdateEnvironmentRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment( + name='name_value', + description='description_value', + agent_version='agent_version_value', + state=environment.Environment.State.STOPPED, + )) + response = await client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.UpdateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.agent_version == 'agent_version_value' + assert response.state == environment.Environment.State.STOPPED + + +@pytest.mark.asyncio +async def test_update_environment_async_from_dict(): + await test_update_environment_async(request_type=dict) + + +def test_update_environment_field_headers(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.UpdateEnvironmentRequest() + + request.environment.name = 'environment.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__call__') as call: + call.return_value = environment.Environment() + client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'environment.name=environment.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_environment_field_headers_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.UpdateEnvironmentRequest() + + request.environment.name = 'environment.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment()) + await client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'environment.name=environment.name/value', + ) in kw['metadata'] + + +def test_delete_environment(transport: str = 'grpc', request_type=environment.DeleteEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.DeleteEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_environment_from_dict(): + test_delete_environment(request_type=dict) + + +def test_delete_environment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=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_environment), + '__call__') as call: + client.delete_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.DeleteEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_delete_environment_async(transport: str = 'grpc_asyncio', request_type=environment.DeleteEnvironmentRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.DeleteEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_environment_async_from_dict(): + await test_delete_environment_async(request_type=dict) + + +def test_delete_environment_field_headers(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.DeleteEnvironmentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__call__') as call: + call.return_value = None + client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_environment_field_headers_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.DeleteEnvironmentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_environment_history(transport: str = 'grpc', request_type=environment.GetEnvironmentHistoryRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_environment_history), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.EnvironmentHistory( + parent='parent_value', + next_page_token='next_page_token_value', + ) + response = client.get_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentHistoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GetEnvironmentHistoryPager) + assert response.parent == 'parent_value' + assert response.next_page_token == 'next_page_token_value' + + +def test_get_environment_history_from_dict(): + test_get_environment_history(request_type=dict) + + +def test_get_environment_history_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=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_environment_history), + '__call__') as call: + client.get_environment_history() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentHistoryRequest() + + +@pytest.mark.asyncio +async def test_get_environment_history_async(transport: str = 'grpc_asyncio', request_type=environment.GetEnvironmentHistoryRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_environment_history), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.EnvironmentHistory( + parent='parent_value', + next_page_token='next_page_token_value', + )) + response = await client.get_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentHistoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GetEnvironmentHistoryAsyncPager) + assert response.parent == 'parent_value' + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_get_environment_history_async_from_dict(): + await test_get_environment_history_async(request_type=dict) + + +def test_get_environment_history_field_headers(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.GetEnvironmentHistoryRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__') as call: + call.return_value = environment.EnvironmentHistory() + client.get_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_get_environment_history_field_headers_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.GetEnvironmentHistoryRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.EnvironmentHistory()) + await client.get_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_get_environment_history_pager(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token='abc', + ), + environment.EnvironmentHistory( + entries=[], + next_page_token='def', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + ], + next_page_token='ghi', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.get_environment_history(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, environment.EnvironmentHistory.Entry) + for i in results) + +def test_get_environment_history_pages(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token='abc', + ), + environment.EnvironmentHistory( + entries=[], + next_page_token='def', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + ], + next_page_token='ghi', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + pages = list(client.get_environment_history(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_get_environment_history_async_pager(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token='abc', + ), + environment.EnvironmentHistory( + entries=[], + next_page_token='def', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + ], + next_page_token='ghi', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + async_pager = await client.get_environment_history(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, environment.EnvironmentHistory.Entry) + for i in responses) + +@pytest.mark.asyncio +async def test_get_environment_history_async_pages(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token='abc', + ), + environment.EnvironmentHistory( + entries=[], + next_page_token='def', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + ], + next_page_token='ghi', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.get_environment_history(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.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = EnvironmentsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.EnvironmentsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.EnvironmentsGrpcTransport, + transports.EnvironmentsGrpcAsyncIOTransport, +]) +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 = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.EnvironmentsGrpcTransport, + ) + +def test_environments_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.EnvironmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_environments_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2.services.environments.transports.EnvironmentsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.EnvironmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_environments', + 'get_environment', + 'create_environment', + 'update_environment', + 'delete_environment', + 'get_environment_history', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_environments_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.dialogflow_v2.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EnvironmentsTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_environments_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.dialogflow_v2.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EnvironmentsTransport() + adc.assert_called_once() + + +def test_environments_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) + EnvironmentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EnvironmentsGrpcTransport, + transports.EnvironmentsGrpcAsyncIOTransport, + ], +) +def test_environments_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EnvironmentsGrpcTransport, grpc_helpers), + (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_environments_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport]) +def test_environments_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_environments_host_no_port(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_environments_host_with_port(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_environments_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EnvironmentsGrpcTransport( + 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_environments_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EnvironmentsGrpcAsyncIOTransport( + 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.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport]) +def test_environments_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.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport]) +def test_environments_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_environment_path(): + project = "squid" + environment = "clam" + expected = "projects/{project}/agent/environments/{environment}".format(project=project, environment=environment, ) + actual = EnvironmentsClient.environment_path(project, environment) + assert expected == actual + + +def test_parse_environment_path(): + expected = { + "project": "whelk", + "environment": "octopus", + } + path = EnvironmentsClient.environment_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_environment_path(path) + assert expected == actual + +def test_fulfillment_path(): + project = "oyster" + expected = "projects/{project}/agent/fulfillment".format(project=project, ) + actual = EnvironmentsClient.fulfillment_path(project) + assert expected == actual + + +def test_parse_fulfillment_path(): + expected = { + "project": "nudibranch", + } + path = EnvironmentsClient.fulfillment_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_fulfillment_path(path) + assert expected == actual + +def test_version_path(): + project = "cuttlefish" + version = "mussel" + expected = "projects/{project}/agent/versions/{version}".format(project=project, version=version, ) + actual = EnvironmentsClient.version_path(project, version) + assert expected == actual + + +def test_parse_version_path(): + expected = { + "project": "winkle", + "version": "nautilus", + } + path = EnvironmentsClient.version_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_version_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = EnvironmentsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = EnvironmentsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = EnvironmentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = EnvironmentsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = EnvironmentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = EnvironmentsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = EnvironmentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = EnvironmentsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.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 = EnvironmentsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = EnvironmentsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.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.EnvironmentsTransport, '_prep_wrapped_messages') as prep: + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.EnvironmentsTransport, '_prep_wrapped_messages') as prep: + transport_class = EnvironmentsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_fulfillments.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_fulfillments.py new file mode 100644 index 000000000..2ed6d866f --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_fulfillments.py @@ -0,0 +1,1414 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.fulfillments import FulfillmentsAsyncClient +from google.cloud.dialogflow_v2.services.fulfillments import FulfillmentsClient +from google.cloud.dialogflow_v2.services.fulfillments import transports +from google.cloud.dialogflow_v2.types import fulfillment +from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert FulfillmentsClient._get_default_mtls_endpoint(None) is None + assert FulfillmentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert FulfillmentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert FulfillmentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert FulfillmentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert FulfillmentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + FulfillmentsClient, + FulfillmentsAsyncClient, +]) +def test_fulfillments_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.FulfillmentsGrpcTransport, "grpc"), + (transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_fulfillments_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + FulfillmentsClient, + FulfillmentsAsyncClient, +]) +def test_fulfillments_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 == 'dialogflow.googleapis.com:443' + + +def test_fulfillments_client_get_transport_class(): + transport = FulfillmentsClient.get_transport_class() + available_transports = [ + transports.FulfillmentsGrpcTransport, + ] + assert transport in available_transports + + transport = FulfillmentsClient.get_transport_class("grpc") + assert transport == transports.FulfillmentsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), + (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(FulfillmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsClient)) +@mock.patch.object(FulfillmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsAsyncClient)) +def test_fulfillments_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(FulfillmentsClient, '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(FulfillmentsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc", "true"), + (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc", "false"), + (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(FulfillmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsClient)) +@mock.patch.object(FulfillmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_fulfillments_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), + (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_fulfillments_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), + (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_fulfillments_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_fulfillments_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2.services.fulfillments.transports.FulfillmentsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = FulfillmentsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_get_fulfillment(transport: str = 'grpc', request_type=fulfillment.GetFulfillmentRequest): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = fulfillment.Fulfillment( + name='name_value', + display_name='display_name_value', + enabled=True, + generic_web_service=fulfillment.Fulfillment.GenericWebService(uri='uri_value'), + ) + response = client.get_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == fulfillment.GetFulfillmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, fulfillment.Fulfillment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enabled is True + + +def test_get_fulfillment_from_dict(): + test_get_fulfillment(request_type=dict) + + +def test_get_fulfillment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FulfillmentsClient( + credentials=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_fulfillment), + '__call__') as call: + client.get_fulfillment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == fulfillment.GetFulfillmentRequest() + + +@pytest.mark.asyncio +async def test_get_fulfillment_async(transport: str = 'grpc_asyncio', request_type=fulfillment.GetFulfillmentRequest): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(fulfillment.Fulfillment( + name='name_value', + display_name='display_name_value', + enabled=True, + )) + response = await client.get_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == fulfillment.GetFulfillmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, fulfillment.Fulfillment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enabled is True + + +@pytest.mark.asyncio +async def test_get_fulfillment_async_from_dict(): + await test_get_fulfillment_async(request_type=dict) + + +def test_get_fulfillment_field_headers(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = fulfillment.GetFulfillmentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_fulfillment), + '__call__') as call: + call.return_value = fulfillment.Fulfillment() + client.get_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_fulfillment_field_headers_async(): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = fulfillment.GetFulfillmentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_fulfillment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(fulfillment.Fulfillment()) + await client.get_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_fulfillment_flattened(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = fulfillment.Fulfillment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_fulfillment( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_fulfillment_flattened_error(): + client = FulfillmentsClient( + credentials=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_fulfillment( + fulfillment.GetFulfillmentRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_fulfillment_flattened_async(): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = fulfillment.Fulfillment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(fulfillment.Fulfillment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_fulfillment( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_fulfillment_flattened_error_async(): + client = FulfillmentsAsyncClient( + credentials=ga_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_fulfillment( + fulfillment.GetFulfillmentRequest(), + name='name_value', + ) + + +def test_update_fulfillment(transport: str = 'grpc', request_type=gcd_fulfillment.UpdateFulfillmentRequest): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_fulfillment.Fulfillment( + name='name_value', + display_name='display_name_value', + enabled=True, + generic_web_service=gcd_fulfillment.Fulfillment.GenericWebService(uri='uri_value'), + ) + response = client.update_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_fulfillment.UpdateFulfillmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_fulfillment.Fulfillment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enabled is True + + +def test_update_fulfillment_from_dict(): + test_update_fulfillment(request_type=dict) + + +def test_update_fulfillment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FulfillmentsClient( + credentials=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_fulfillment), + '__call__') as call: + client.update_fulfillment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_fulfillment.UpdateFulfillmentRequest() + + +@pytest.mark.asyncio +async def test_update_fulfillment_async(transport: str = 'grpc_asyncio', request_type=gcd_fulfillment.UpdateFulfillmentRequest): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_fulfillment.Fulfillment( + name='name_value', + display_name='display_name_value', + enabled=True, + )) + response = await client.update_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_fulfillment.UpdateFulfillmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_fulfillment.Fulfillment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enabled is True + + +@pytest.mark.asyncio +async def test_update_fulfillment_async_from_dict(): + await test_update_fulfillment_async(request_type=dict) + + +def test_update_fulfillment_field_headers(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_fulfillment.UpdateFulfillmentRequest() + + request.fulfillment.name = 'fulfillment.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), + '__call__') as call: + call.return_value = gcd_fulfillment.Fulfillment() + client.update_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'fulfillment.name=fulfillment.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_fulfillment_field_headers_async(): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_fulfillment.UpdateFulfillmentRequest() + + request.fulfillment.name = 'fulfillment.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_fulfillment.Fulfillment()) + await client.update_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'fulfillment.name=fulfillment.name/value', + ) in kw['metadata'] + + +def test_update_fulfillment_flattened(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_fulfillment.Fulfillment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_fulfillment( + fulfillment=gcd_fulfillment.Fulfillment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].fulfillment + mock_val = gcd_fulfillment.Fulfillment(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_fulfillment_flattened_error(): + client = FulfillmentsClient( + credentials=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_fulfillment( + gcd_fulfillment.UpdateFulfillmentRequest(), + fulfillment=gcd_fulfillment.Fulfillment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_fulfillment_flattened_async(): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_fulfillment.Fulfillment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_fulfillment.Fulfillment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_fulfillment( + fulfillment=gcd_fulfillment.Fulfillment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].fulfillment + mock_val = gcd_fulfillment.Fulfillment(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_fulfillment_flattened_error_async(): + client = FulfillmentsAsyncClient( + credentials=ga_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_fulfillment( + gcd_fulfillment.UpdateFulfillmentRequest(), + fulfillment=gcd_fulfillment.Fulfillment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FulfillmentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FulfillmentsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = FulfillmentsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.FulfillmentsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.FulfillmentsGrpcTransport, + transports.FulfillmentsGrpcAsyncIOTransport, +]) +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 = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.FulfillmentsGrpcTransport, + ) + +def test_fulfillments_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.FulfillmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_fulfillments_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2.services.fulfillments.transports.FulfillmentsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.FulfillmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_fulfillment', + 'update_fulfillment', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_fulfillments_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.dialogflow_v2.services.fulfillments.transports.FulfillmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FulfillmentsTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_fulfillments_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.dialogflow_v2.services.fulfillments.transports.FulfillmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FulfillmentsTransport() + adc.assert_called_once() + + +def test_fulfillments_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) + FulfillmentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FulfillmentsGrpcTransport, + transports.FulfillmentsGrpcAsyncIOTransport, + ], +) +def test_fulfillments_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FulfillmentsGrpcTransport, grpc_helpers), + (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_fulfillments_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.FulfillmentsGrpcTransport, transports.FulfillmentsGrpcAsyncIOTransport]) +def test_fulfillments_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_fulfillments_host_no_port(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_fulfillments_host_with_port(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_fulfillments_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FulfillmentsGrpcTransport( + 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_fulfillments_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FulfillmentsGrpcAsyncIOTransport( + 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.FulfillmentsGrpcTransport, transports.FulfillmentsGrpcAsyncIOTransport]) +def test_fulfillments_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.FulfillmentsGrpcTransport, transports.FulfillmentsGrpcAsyncIOTransport]) +def test_fulfillments_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_fulfillment_path(): + project = "squid" + expected = "projects/{project}/agent/fulfillment".format(project=project, ) + actual = FulfillmentsClient.fulfillment_path(project) + assert expected == actual + + +def test_parse_fulfillment_path(): + expected = { + "project": "clam", + } + path = FulfillmentsClient.fulfillment_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_fulfillment_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = FulfillmentsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = FulfillmentsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = FulfillmentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = FulfillmentsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = FulfillmentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = FulfillmentsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = FulfillmentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = FulfillmentsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = FulfillmentsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = FulfillmentsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.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.FulfillmentsTransport, '_prep_wrapped_messages') as prep: + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.FulfillmentsTransport, '_prep_wrapped_messages') as prep: + transport_class = FulfillmentsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_intents.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_intents.py new file mode 100644 index 000000000..5b235e61b --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_intents.py @@ -0,0 +1,3059 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.intents import IntentsAsyncClient +from google.cloud.dialogflow_v2.services.intents import IntentsClient +from google.cloud.dialogflow_v2.services.intents import pagers +from google.cloud.dialogflow_v2.services.intents import transports +from google.cloud.dialogflow_v2.types import context +from google.cloud.dialogflow_v2.types import intent +from google.cloud.dialogflow_v2.types import intent as gcd_intent +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 struct_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert IntentsClient._get_default_mtls_endpoint(None) is None + assert IntentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert IntentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert IntentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert IntentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert IntentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + IntentsClient, + IntentsAsyncClient, +]) +def test_intents_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.IntentsGrpcTransport, "grpc"), + (transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_intents_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + IntentsClient, + IntentsAsyncClient, +]) +def test_intents_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 == 'dialogflow.googleapis.com:443' + + +def test_intents_client_get_transport_class(): + transport = IntentsClient.get_transport_class() + available_transports = [ + transports.IntentsGrpcTransport, + ] + assert transport in available_transports + + transport = IntentsClient.get_transport_class("grpc") + assert transport == transports.IntentsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (IntentsClient, transports.IntentsGrpcTransport, "grpc"), + (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(IntentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IntentsClient)) +@mock.patch.object(IntentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IntentsAsyncClient)) +def test_intents_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(IntentsClient, '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(IntentsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (IntentsClient, transports.IntentsGrpcTransport, "grpc", "true"), + (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (IntentsClient, transports.IntentsGrpcTransport, "grpc", "false"), + (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(IntentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IntentsClient)) +@mock.patch.object(IntentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IntentsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_intents_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (IntentsClient, transports.IntentsGrpcTransport, "grpc"), + (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_intents_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (IntentsClient, transports.IntentsGrpcTransport, "grpc"), + (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_intents_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_intents_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2.services.intents.transports.IntentsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = IntentsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_intents(transport: str = 'grpc', request_type=intent.ListIntentsRequest): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_intents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = intent.ListIntentsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_intents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == intent.ListIntentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListIntentsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_intents_from_dict(): + test_list_intents(request_type=dict) + + +def test_list_intents_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IntentsClient( + credentials=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_intents), + '__call__') as call: + client.list_intents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == intent.ListIntentsRequest() + + +@pytest.mark.asyncio +async def test_list_intents_async(transport: str = 'grpc_asyncio', request_type=intent.ListIntentsRequest): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_intents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(intent.ListIntentsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_intents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == intent.ListIntentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListIntentsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_intents_async_from_dict(): + await test_list_intents_async(request_type=dict) + + +def test_list_intents_field_headers(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = intent.ListIntentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intents), + '__call__') as call: + call.return_value = intent.ListIntentsResponse() + client.list_intents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_intents_field_headers_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = intent.ListIntentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(intent.ListIntentsResponse()) + await client.list_intents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_intents_flattened(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = intent.ListIntentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_intents( + parent='parent_value', + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +def test_list_intents_flattened_error(): + client = IntentsClient( + credentials=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_intents( + intent.ListIntentsRequest(), + parent='parent_value', + language_code='language_code_value', + ) + + +@pytest.mark.asyncio +async def test_list_intents_flattened_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = intent.ListIntentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(intent.ListIntentsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_intents( + parent='parent_value', + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_intents_flattened_error_async(): + client = IntentsAsyncClient( + credentials=ga_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_intents( + intent.ListIntentsRequest(), + parent='parent_value', + language_code='language_code_value', + ) + + +def test_list_intents_pager(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intents), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + intent.ListIntentsResponse( + intents=[ + intent.Intent(), + intent.Intent(), + intent.Intent(), + ], + next_page_token='abc', + ), + intent.ListIntentsResponse( + intents=[], + next_page_token='def', + ), + intent.ListIntentsResponse( + intents=[ + intent.Intent(), + ], + next_page_token='ghi', + ), + intent.ListIntentsResponse( + intents=[ + intent.Intent(), + intent.Intent(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_intents(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, intent.Intent) + for i in results) + +def test_list_intents_pages(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intents), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + intent.ListIntentsResponse( + intents=[ + intent.Intent(), + intent.Intent(), + intent.Intent(), + ], + next_page_token='abc', + ), + intent.ListIntentsResponse( + intents=[], + next_page_token='def', + ), + intent.ListIntentsResponse( + intents=[ + intent.Intent(), + ], + next_page_token='ghi', + ), + intent.ListIntentsResponse( + intents=[ + intent.Intent(), + intent.Intent(), + ], + ), + RuntimeError, + ) + pages = list(client.list_intents(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_intents_async_pager(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intents), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + intent.ListIntentsResponse( + intents=[ + intent.Intent(), + intent.Intent(), + intent.Intent(), + ], + next_page_token='abc', + ), + intent.ListIntentsResponse( + intents=[], + next_page_token='def', + ), + intent.ListIntentsResponse( + intents=[ + intent.Intent(), + ], + next_page_token='ghi', + ), + intent.ListIntentsResponse( + intents=[ + intent.Intent(), + intent.Intent(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_intents(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, intent.Intent) + for i in responses) + +@pytest.mark.asyncio +async def test_list_intents_async_pages(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intents), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + intent.ListIntentsResponse( + intents=[ + intent.Intent(), + intent.Intent(), + intent.Intent(), + ], + next_page_token='abc', + ), + intent.ListIntentsResponse( + intents=[], + next_page_token='def', + ), + intent.ListIntentsResponse( + intents=[ + intent.Intent(), + ], + next_page_token='ghi', + ), + intent.ListIntentsResponse( + intents=[ + intent.Intent(), + intent.Intent(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_intents(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_intent(transport: str = 'grpc', request_type=intent.GetIntentRequest): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = intent.Intent( + name='name_value', + display_name='display_name_value', + webhook_state=intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, + priority=898, + is_fallback=True, + ml_disabled=True, + live_agent_handoff=True, + end_interaction=True, + input_context_names=['input_context_names_value'], + events=['events_value'], + action='action_value', + reset_contexts=True, + default_response_platforms=[intent.Intent.Message.Platform.FACEBOOK], + root_followup_intent_name='root_followup_intent_name_value', + parent_followup_intent_name='parent_followup_intent_name_value', + ) + response = client.get_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == intent.GetIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, intent.Intent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.webhook_state == intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED + assert response.priority == 898 + assert response.is_fallback is True + assert response.ml_disabled is True + assert response.live_agent_handoff is True + assert response.end_interaction is True + assert response.input_context_names == ['input_context_names_value'] + assert response.events == ['events_value'] + assert response.action == 'action_value' + assert response.reset_contexts is True + assert response.default_response_platforms == [intent.Intent.Message.Platform.FACEBOOK] + assert response.root_followup_intent_name == 'root_followup_intent_name_value' + assert response.parent_followup_intent_name == 'parent_followup_intent_name_value' + + +def test_get_intent_from_dict(): + test_get_intent(request_type=dict) + + +def test_get_intent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IntentsClient( + credentials=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_intent), + '__call__') as call: + client.get_intent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == intent.GetIntentRequest() + + +@pytest.mark.asyncio +async def test_get_intent_async(transport: str = 'grpc_asyncio', request_type=intent.GetIntentRequest): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(intent.Intent( + name='name_value', + display_name='display_name_value', + webhook_state=intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, + priority=898, + is_fallback=True, + ml_disabled=True, + live_agent_handoff=True, + end_interaction=True, + input_context_names=['input_context_names_value'], + events=['events_value'], + action='action_value', + reset_contexts=True, + default_response_platforms=[intent.Intent.Message.Platform.FACEBOOK], + root_followup_intent_name='root_followup_intent_name_value', + parent_followup_intent_name='parent_followup_intent_name_value', + )) + response = await client.get_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == intent.GetIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, intent.Intent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.webhook_state == intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED + assert response.priority == 898 + assert response.is_fallback is True + assert response.ml_disabled is True + assert response.live_agent_handoff is True + assert response.end_interaction is True + assert response.input_context_names == ['input_context_names_value'] + assert response.events == ['events_value'] + assert response.action == 'action_value' + assert response.reset_contexts is True + assert response.default_response_platforms == [intent.Intent.Message.Platform.FACEBOOK] + assert response.root_followup_intent_name == 'root_followup_intent_name_value' + assert response.parent_followup_intent_name == 'parent_followup_intent_name_value' + + +@pytest.mark.asyncio +async def test_get_intent_async_from_dict(): + await test_get_intent_async(request_type=dict) + + +def test_get_intent_field_headers(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = intent.GetIntentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_intent), + '__call__') as call: + call.return_value = intent.Intent() + client.get_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_intent_field_headers_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = intent.GetIntentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_intent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(intent.Intent()) + await client.get_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_intent_flattened(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = intent.Intent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_intent( + name='name_value', + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +def test_get_intent_flattened_error(): + client = IntentsClient( + credentials=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_intent( + intent.GetIntentRequest(), + name='name_value', + language_code='language_code_value', + ) + + +@pytest.mark.asyncio +async def test_get_intent_flattened_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = intent.Intent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(intent.Intent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_intent( + name='name_value', + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_intent_flattened_error_async(): + client = IntentsAsyncClient( + credentials=ga_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_intent( + intent.GetIntentRequest(), + name='name_value', + language_code='language_code_value', + ) + + +def test_create_intent(transport: str = 'grpc', request_type=gcd_intent.CreateIntentRequest): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_intent.Intent( + name='name_value', + display_name='display_name_value', + webhook_state=gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, + priority=898, + is_fallback=True, + ml_disabled=True, + live_agent_handoff=True, + end_interaction=True, + input_context_names=['input_context_names_value'], + events=['events_value'], + action='action_value', + reset_contexts=True, + default_response_platforms=[gcd_intent.Intent.Message.Platform.FACEBOOK], + root_followup_intent_name='root_followup_intent_name_value', + parent_followup_intent_name='parent_followup_intent_name_value', + ) + response = client.create_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_intent.CreateIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_intent.Intent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.webhook_state == gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED + assert response.priority == 898 + assert response.is_fallback is True + assert response.ml_disabled is True + assert response.live_agent_handoff is True + assert response.end_interaction is True + assert response.input_context_names == ['input_context_names_value'] + assert response.events == ['events_value'] + assert response.action == 'action_value' + assert response.reset_contexts is True + assert response.default_response_platforms == [gcd_intent.Intent.Message.Platform.FACEBOOK] + assert response.root_followup_intent_name == 'root_followup_intent_name_value' + assert response.parent_followup_intent_name == 'parent_followup_intent_name_value' + + +def test_create_intent_from_dict(): + test_create_intent(request_type=dict) + + +def test_create_intent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IntentsClient( + credentials=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_intent), + '__call__') as call: + client.create_intent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_intent.CreateIntentRequest() + + +@pytest.mark.asyncio +async def test_create_intent_async(transport: str = 'grpc_asyncio', request_type=gcd_intent.CreateIntentRequest): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent( + name='name_value', + display_name='display_name_value', + webhook_state=gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, + priority=898, + is_fallback=True, + ml_disabled=True, + live_agent_handoff=True, + end_interaction=True, + input_context_names=['input_context_names_value'], + events=['events_value'], + action='action_value', + reset_contexts=True, + default_response_platforms=[gcd_intent.Intent.Message.Platform.FACEBOOK], + root_followup_intent_name='root_followup_intent_name_value', + parent_followup_intent_name='parent_followup_intent_name_value', + )) + response = await client.create_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_intent.CreateIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_intent.Intent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.webhook_state == gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED + assert response.priority == 898 + assert response.is_fallback is True + assert response.ml_disabled is True + assert response.live_agent_handoff is True + assert response.end_interaction is True + assert response.input_context_names == ['input_context_names_value'] + assert response.events == ['events_value'] + assert response.action == 'action_value' + assert response.reset_contexts is True + assert response.default_response_platforms == [gcd_intent.Intent.Message.Platform.FACEBOOK] + assert response.root_followup_intent_name == 'root_followup_intent_name_value' + assert response.parent_followup_intent_name == 'parent_followup_intent_name_value' + + +@pytest.mark.asyncio +async def test_create_intent_async_from_dict(): + await test_create_intent_async(request_type=dict) + + +def test_create_intent_field_headers(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_intent.CreateIntentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_intent), + '__call__') as call: + call.return_value = gcd_intent.Intent() + client.create_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_intent_field_headers_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_intent.CreateIntentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_intent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent()) + await client.create_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_intent_flattened(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_intent.Intent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_intent( + parent='parent_value', + intent=gcd_intent.Intent(name='name_value'), + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].intent + mock_val = gcd_intent.Intent(name='name_value') + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +def test_create_intent_flattened_error(): + client = IntentsClient( + credentials=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_intent( + gcd_intent.CreateIntentRequest(), + parent='parent_value', + intent=gcd_intent.Intent(name='name_value'), + language_code='language_code_value', + ) + + +@pytest.mark.asyncio +async def test_create_intent_flattened_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_intent.Intent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_intent( + parent='parent_value', + intent=gcd_intent.Intent(name='name_value'), + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].intent + mock_val = gcd_intent.Intent(name='name_value') + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_intent_flattened_error_async(): + client = IntentsAsyncClient( + credentials=ga_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_intent( + gcd_intent.CreateIntentRequest(), + parent='parent_value', + intent=gcd_intent.Intent(name='name_value'), + language_code='language_code_value', + ) + + +def test_update_intent(transport: str = 'grpc', request_type=gcd_intent.UpdateIntentRequest): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_intent.Intent( + name='name_value', + display_name='display_name_value', + webhook_state=gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, + priority=898, + is_fallback=True, + ml_disabled=True, + live_agent_handoff=True, + end_interaction=True, + input_context_names=['input_context_names_value'], + events=['events_value'], + action='action_value', + reset_contexts=True, + default_response_platforms=[gcd_intent.Intent.Message.Platform.FACEBOOK], + root_followup_intent_name='root_followup_intent_name_value', + parent_followup_intent_name='parent_followup_intent_name_value', + ) + response = client.update_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_intent.UpdateIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_intent.Intent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.webhook_state == gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED + assert response.priority == 898 + assert response.is_fallback is True + assert response.ml_disabled is True + assert response.live_agent_handoff is True + assert response.end_interaction is True + assert response.input_context_names == ['input_context_names_value'] + assert response.events == ['events_value'] + assert response.action == 'action_value' + assert response.reset_contexts is True + assert response.default_response_platforms == [gcd_intent.Intent.Message.Platform.FACEBOOK] + assert response.root_followup_intent_name == 'root_followup_intent_name_value' + assert response.parent_followup_intent_name == 'parent_followup_intent_name_value' + + +def test_update_intent_from_dict(): + test_update_intent(request_type=dict) + + +def test_update_intent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IntentsClient( + credentials=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_intent), + '__call__') as call: + client.update_intent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_intent.UpdateIntentRequest() + + +@pytest.mark.asyncio +async def test_update_intent_async(transport: str = 'grpc_asyncio', request_type=gcd_intent.UpdateIntentRequest): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent( + name='name_value', + display_name='display_name_value', + webhook_state=gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, + priority=898, + is_fallback=True, + ml_disabled=True, + live_agent_handoff=True, + end_interaction=True, + input_context_names=['input_context_names_value'], + events=['events_value'], + action='action_value', + reset_contexts=True, + default_response_platforms=[gcd_intent.Intent.Message.Platform.FACEBOOK], + root_followup_intent_name='root_followup_intent_name_value', + parent_followup_intent_name='parent_followup_intent_name_value', + )) + response = await client.update_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_intent.UpdateIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_intent.Intent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.webhook_state == gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED + assert response.priority == 898 + assert response.is_fallback is True + assert response.ml_disabled is True + assert response.live_agent_handoff is True + assert response.end_interaction is True + assert response.input_context_names == ['input_context_names_value'] + assert response.events == ['events_value'] + assert response.action == 'action_value' + assert response.reset_contexts is True + assert response.default_response_platforms == [gcd_intent.Intent.Message.Platform.FACEBOOK] + assert response.root_followup_intent_name == 'root_followup_intent_name_value' + assert response.parent_followup_intent_name == 'parent_followup_intent_name_value' + + +@pytest.mark.asyncio +async def test_update_intent_async_from_dict(): + await test_update_intent_async(request_type=dict) + + +def test_update_intent_field_headers(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_intent.UpdateIntentRequest() + + request.intent.name = 'intent.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_intent), + '__call__') as call: + call.return_value = gcd_intent.Intent() + client.update_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'intent.name=intent.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_intent_field_headers_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_intent.UpdateIntentRequest() + + request.intent.name = 'intent.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_intent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent()) + await client.update_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'intent.name=intent.name/value', + ) in kw['metadata'] + + +def test_update_intent_flattened(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_intent.Intent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_intent( + intent=gcd_intent.Intent(name='name_value'), + language_code='language_code_value', + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].intent + mock_val = gcd_intent.Intent(name='name_value') + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_intent_flattened_error(): + client = IntentsClient( + credentials=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_intent( + gcd_intent.UpdateIntentRequest(), + intent=gcd_intent.Intent(name='name_value'), + language_code='language_code_value', + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_intent_flattened_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_intent.Intent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_intent( + intent=gcd_intent.Intent(name='name_value'), + language_code='language_code_value', + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].intent + mock_val = gcd_intent.Intent(name='name_value') + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_intent_flattened_error_async(): + client = IntentsAsyncClient( + credentials=ga_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_intent( + gcd_intent.UpdateIntentRequest(), + intent=gcd_intent.Intent(name='name_value'), + language_code='language_code_value', + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_intent(transport: str = 'grpc', request_type=intent.DeleteIntentRequest): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == intent.DeleteIntentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_intent_from_dict(): + test_delete_intent(request_type=dict) + + +def test_delete_intent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IntentsClient( + credentials=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_intent), + '__call__') as call: + client.delete_intent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == intent.DeleteIntentRequest() + + +@pytest.mark.asyncio +async def test_delete_intent_async(transport: str = 'grpc_asyncio', request_type=intent.DeleteIntentRequest): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == intent.DeleteIntentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_intent_async_from_dict(): + await test_delete_intent_async(request_type=dict) + + +def test_delete_intent_field_headers(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = intent.DeleteIntentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_intent), + '__call__') as call: + call.return_value = None + client.delete_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_intent_field_headers_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = intent.DeleteIntentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_intent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_intent_flattened(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_intent), + '__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_intent( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_intent_flattened_error(): + client = IntentsClient( + credentials=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_intent( + intent.DeleteIntentRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_intent_flattened_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_intent), + '__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_intent( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_intent_flattened_error_async(): + client = IntentsAsyncClient( + credentials=ga_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_intent( + intent.DeleteIntentRequest(), + name='name_value', + ) + + +def test_batch_update_intents(transport: str = 'grpc', request_type=intent.BatchUpdateIntentsRequest): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_intents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.batch_update_intents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == intent.BatchUpdateIntentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_update_intents_from_dict(): + test_batch_update_intents(request_type=dict) + + +def test_batch_update_intents_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_intents), + '__call__') as call: + client.batch_update_intents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == intent.BatchUpdateIntentsRequest() + + +@pytest.mark.asyncio +async def test_batch_update_intents_async(transport: str = 'grpc_asyncio', request_type=intent.BatchUpdateIntentsRequest): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_intents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.batch_update_intents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == intent.BatchUpdateIntentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_update_intents_async_from_dict(): + await test_batch_update_intents_async(request_type=dict) + + +def test_batch_update_intents_field_headers(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = intent.BatchUpdateIntentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_intents), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.batch_update_intents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_batch_update_intents_field_headers_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = intent.BatchUpdateIntentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_intents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.batch_update_intents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_batch_update_intents_flattened(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_intents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_update_intents( + parent='parent_value', + intent_batch_uri='intent_batch_uri_value', + intent_batch_inline=intent.IntentBatch(intents=[intent.Intent(name='name_value')]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + assert args[0].intent_batch_inline == intent.IntentBatch(intents=[intent.Intent(name='name_value')]) + + +def test_batch_update_intents_flattened_error(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_update_intents( + intent.BatchUpdateIntentsRequest(), + parent='parent_value', + intent_batch_uri='intent_batch_uri_value', + intent_batch_inline=intent.IntentBatch(intents=[intent.Intent(name='name_value')]), + ) + + +@pytest.mark.asyncio +async def test_batch_update_intents_flattened_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_intents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_update_intents( + parent='parent_value', + intent_batch_uri='intent_batch_uri_value', + intent_batch_inline=intent.IntentBatch(intents=[intent.Intent(name='name_value')]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + assert args[0].intent_batch_inline == intent.IntentBatch(intents=[intent.Intent(name='name_value')]) + + +@pytest.mark.asyncio +async def test_batch_update_intents_flattened_error_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_update_intents( + intent.BatchUpdateIntentsRequest(), + parent='parent_value', + intent_batch_uri='intent_batch_uri_value', + intent_batch_inline=intent.IntentBatch(intents=[intent.Intent(name='name_value')]), + ) + + +def test_batch_delete_intents(transport: str = 'grpc', request_type=intent.BatchDeleteIntentsRequest): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_intents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.batch_delete_intents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == intent.BatchDeleteIntentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_delete_intents_from_dict(): + test_batch_delete_intents(request_type=dict) + + +def test_batch_delete_intents_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_intents), + '__call__') as call: + client.batch_delete_intents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == intent.BatchDeleteIntentsRequest() + + +@pytest.mark.asyncio +async def test_batch_delete_intents_async(transport: str = 'grpc_asyncio', request_type=intent.BatchDeleteIntentsRequest): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_intents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.batch_delete_intents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == intent.BatchDeleteIntentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_delete_intents_async_from_dict(): + await test_batch_delete_intents_async(request_type=dict) + + +def test_batch_delete_intents_field_headers(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = intent.BatchDeleteIntentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_intents), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.batch_delete_intents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_batch_delete_intents_field_headers_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = intent.BatchDeleteIntentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_intents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.batch_delete_intents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_batch_delete_intents_flattened(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_intents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_delete_intents( + parent='parent_value', + intents=[intent.Intent(name='name_value')], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].intents + mock_val = [intent.Intent(name='name_value')] + assert arg == mock_val + + +def test_batch_delete_intents_flattened_error(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_delete_intents( + intent.BatchDeleteIntentsRequest(), + parent='parent_value', + intents=[intent.Intent(name='name_value')], + ) + + +@pytest.mark.asyncio +async def test_batch_delete_intents_flattened_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_intents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_delete_intents( + parent='parent_value', + intents=[intent.Intent(name='name_value')], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].intents + mock_val = [intent.Intent(name='name_value')] + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_batch_delete_intents_flattened_error_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_delete_intents( + intent.BatchDeleteIntentsRequest(), + parent='parent_value', + intents=[intent.Intent(name='name_value')], + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.IntentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.IntentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = IntentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.IntentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = IntentsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.IntentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = IntentsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.IntentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.IntentsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.IntentsGrpcTransport, + transports.IntentsGrpcAsyncIOTransport, +]) +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 = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.IntentsGrpcTransport, + ) + +def test_intents_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.IntentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_intents_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2.services.intents.transports.IntentsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.IntentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_intents', + 'get_intent', + 'create_intent', + 'update_intent', + 'delete_intent', + 'batch_update_intents', + 'batch_delete_intents', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +def test_intents_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.dialogflow_v2.services.intents.transports.IntentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.IntentsTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_intents_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.dialogflow_v2.services.intents.transports.IntentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.IntentsTransport() + adc.assert_called_once() + + +def test_intents_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) + IntentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.IntentsGrpcTransport, + transports.IntentsGrpcAsyncIOTransport, + ], +) +def test_intents_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.IntentsGrpcTransport, grpc_helpers), + (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_intents_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport]) +def test_intents_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_intents_host_no_port(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_intents_host_with_port(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_intents_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.IntentsGrpcTransport( + 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_intents_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.IntentsGrpcAsyncIOTransport( + 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.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport]) +def test_intents_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.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport]) +def test_intents_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_intents_grpc_lro_client(): + client = IntentsClient( + 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_intents_grpc_lro_async_client(): + client = IntentsAsyncClient( + 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_context_path(): + project = "squid" + session = "clam" + context = "whelk" + expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) + actual = IntentsClient.context_path(project, session, context) + assert expected == actual + + +def test_parse_context_path(): + expected = { + "project": "octopus", + "session": "oyster", + "context": "nudibranch", + } + path = IntentsClient.context_path(**expected) + + # Check that the path construction is reversible. + actual = IntentsClient.parse_context_path(path) + assert expected == actual + +def test_intent_path(): + project = "cuttlefish" + intent = "mussel" + expected = "projects/{project}/agent/intents/{intent}".format(project=project, intent=intent, ) + actual = IntentsClient.intent_path(project, intent) + assert expected == actual + + +def test_parse_intent_path(): + expected = { + "project": "winkle", + "intent": "nautilus", + } + path = IntentsClient.intent_path(**expected) + + # Check that the path construction is reversible. + actual = IntentsClient.parse_intent_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = IntentsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = IntentsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = IntentsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = IntentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = IntentsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = IntentsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = IntentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = IntentsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = IntentsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = IntentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = IntentsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = IntentsClient.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 = IntentsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = IntentsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = IntentsClient.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.IntentsTransport, '_prep_wrapped_messages') as prep: + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.IntentsTransport, '_prep_wrapped_messages') as prep: + transport_class = IntentsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_knowledge_bases.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_knowledge_bases.py new file mode 100644 index 000000000..8cf3f4910 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_knowledge_bases.py @@ -0,0 +1,2321 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.knowledge_bases import KnowledgeBasesAsyncClient +from google.cloud.dialogflow_v2.services.knowledge_bases import KnowledgeBasesClient +from google.cloud.dialogflow_v2.services.knowledge_bases import pagers +from google.cloud.dialogflow_v2.services.knowledge_bases import transports +from google.cloud.dialogflow_v2.types import knowledge_base +from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert KnowledgeBasesClient._get_default_mtls_endpoint(None) is None + assert KnowledgeBasesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert KnowledgeBasesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert KnowledgeBasesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert KnowledgeBasesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert KnowledgeBasesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + KnowledgeBasesClient, + KnowledgeBasesAsyncClient, +]) +def test_knowledge_bases_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.KnowledgeBasesGrpcTransport, "grpc"), + (transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_knowledge_bases_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + KnowledgeBasesClient, + KnowledgeBasesAsyncClient, +]) +def test_knowledge_bases_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 == 'dialogflow.googleapis.com:443' + + +def test_knowledge_bases_client_get_transport_class(): + transport = KnowledgeBasesClient.get_transport_class() + available_transports = [ + transports.KnowledgeBasesGrpcTransport, + ] + assert transport in available_transports + + transport = KnowledgeBasesClient.get_transport_class("grpc") + assert transport == transports.KnowledgeBasesGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc"), + (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(KnowledgeBasesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KnowledgeBasesClient)) +@mock.patch.object(KnowledgeBasesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KnowledgeBasesAsyncClient)) +def test_knowledge_bases_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(KnowledgeBasesClient, '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(KnowledgeBasesClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc", "true"), + (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc", "false"), + (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(KnowledgeBasesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KnowledgeBasesClient)) +@mock.patch.object(KnowledgeBasesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KnowledgeBasesAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_knowledge_bases_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc"), + (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_knowledge_bases_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc"), + (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_knowledge_bases_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_knowledge_bases_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2.services.knowledge_bases.transports.KnowledgeBasesGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = KnowledgeBasesClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_knowledge_bases(transport: str = 'grpc', request_type=knowledge_base.ListKnowledgeBasesRequest): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_knowledge_bases), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = knowledge_base.ListKnowledgeBasesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_knowledge_bases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == knowledge_base.ListKnowledgeBasesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListKnowledgeBasesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_knowledge_bases_from_dict(): + test_list_knowledge_bases(request_type=dict) + + +def test_list_knowledge_bases_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = KnowledgeBasesClient( + credentials=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_knowledge_bases), + '__call__') as call: + client.list_knowledge_bases() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == knowledge_base.ListKnowledgeBasesRequest() + + +@pytest.mark.asyncio +async def test_list_knowledge_bases_async(transport: str = 'grpc_asyncio', request_type=knowledge_base.ListKnowledgeBasesRequest): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_knowledge_bases), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(knowledge_base.ListKnowledgeBasesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_knowledge_bases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == knowledge_base.ListKnowledgeBasesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListKnowledgeBasesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_knowledge_bases_async_from_dict(): + await test_list_knowledge_bases_async(request_type=dict) + + +def test_list_knowledge_bases_field_headers(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = knowledge_base.ListKnowledgeBasesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_knowledge_bases), + '__call__') as call: + call.return_value = knowledge_base.ListKnowledgeBasesResponse() + client.list_knowledge_bases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_knowledge_bases_field_headers_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = knowledge_base.ListKnowledgeBasesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_knowledge_bases), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(knowledge_base.ListKnowledgeBasesResponse()) + await client.list_knowledge_bases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_knowledge_bases_flattened(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_knowledge_bases), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = knowledge_base.ListKnowledgeBasesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_knowledge_bases( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_knowledge_bases_flattened_error(): + client = KnowledgeBasesClient( + credentials=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_knowledge_bases( + knowledge_base.ListKnowledgeBasesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_knowledge_bases_flattened_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_knowledge_bases), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = knowledge_base.ListKnowledgeBasesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(knowledge_base.ListKnowledgeBasesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_knowledge_bases( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_knowledge_bases_flattened_error_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_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_knowledge_bases( + knowledge_base.ListKnowledgeBasesRequest(), + parent='parent_value', + ) + + +def test_list_knowledge_bases_pager(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_knowledge_bases), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[ + knowledge_base.KnowledgeBase(), + knowledge_base.KnowledgeBase(), + knowledge_base.KnowledgeBase(), + ], + next_page_token='abc', + ), + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[], + next_page_token='def', + ), + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[ + knowledge_base.KnowledgeBase(), + ], + next_page_token='ghi', + ), + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[ + knowledge_base.KnowledgeBase(), + knowledge_base.KnowledgeBase(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_knowledge_bases(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, knowledge_base.KnowledgeBase) + for i in results) + +def test_list_knowledge_bases_pages(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_knowledge_bases), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[ + knowledge_base.KnowledgeBase(), + knowledge_base.KnowledgeBase(), + knowledge_base.KnowledgeBase(), + ], + next_page_token='abc', + ), + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[], + next_page_token='def', + ), + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[ + knowledge_base.KnowledgeBase(), + ], + next_page_token='ghi', + ), + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[ + knowledge_base.KnowledgeBase(), + knowledge_base.KnowledgeBase(), + ], + ), + RuntimeError, + ) + pages = list(client.list_knowledge_bases(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_knowledge_bases_async_pager(): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_knowledge_bases), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[ + knowledge_base.KnowledgeBase(), + knowledge_base.KnowledgeBase(), + knowledge_base.KnowledgeBase(), + ], + next_page_token='abc', + ), + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[], + next_page_token='def', + ), + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[ + knowledge_base.KnowledgeBase(), + ], + next_page_token='ghi', + ), + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[ + knowledge_base.KnowledgeBase(), + knowledge_base.KnowledgeBase(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_knowledge_bases(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, knowledge_base.KnowledgeBase) + for i in responses) + +@pytest.mark.asyncio +async def test_list_knowledge_bases_async_pages(): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_knowledge_bases), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[ + knowledge_base.KnowledgeBase(), + knowledge_base.KnowledgeBase(), + knowledge_base.KnowledgeBase(), + ], + next_page_token='abc', + ), + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[], + next_page_token='def', + ), + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[ + knowledge_base.KnowledgeBase(), + ], + next_page_token='ghi', + ), + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[ + knowledge_base.KnowledgeBase(), + knowledge_base.KnowledgeBase(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_knowledge_bases(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_knowledge_base(transport: str = 'grpc', request_type=knowledge_base.GetKnowledgeBaseRequest): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = knowledge_base.KnowledgeBase( + name='name_value', + display_name='display_name_value', + language_code='language_code_value', + ) + response = client.get_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == knowledge_base.GetKnowledgeBaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, knowledge_base.KnowledgeBase) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.language_code == 'language_code_value' + + +def test_get_knowledge_base_from_dict(): + test_get_knowledge_base(request_type=dict) + + +def test_get_knowledge_base_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = KnowledgeBasesClient( + credentials=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_knowledge_base), + '__call__') as call: + client.get_knowledge_base() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == knowledge_base.GetKnowledgeBaseRequest() + + +@pytest.mark.asyncio +async def test_get_knowledge_base_async(transport: str = 'grpc_asyncio', request_type=knowledge_base.GetKnowledgeBaseRequest): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(knowledge_base.KnowledgeBase( + name='name_value', + display_name='display_name_value', + language_code='language_code_value', + )) + response = await client.get_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == knowledge_base.GetKnowledgeBaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, knowledge_base.KnowledgeBase) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_get_knowledge_base_async_from_dict(): + await test_get_knowledge_base_async(request_type=dict) + + +def test_get_knowledge_base_field_headers(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = knowledge_base.GetKnowledgeBaseRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_knowledge_base), + '__call__') as call: + call.return_value = knowledge_base.KnowledgeBase() + client.get_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_knowledge_base_field_headers_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = knowledge_base.GetKnowledgeBaseRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_knowledge_base), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(knowledge_base.KnowledgeBase()) + await client.get_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_knowledge_base_flattened(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = knowledge_base.KnowledgeBase() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_knowledge_base( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_knowledge_base_flattened_error(): + client = KnowledgeBasesClient( + credentials=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_knowledge_base( + knowledge_base.GetKnowledgeBaseRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_knowledge_base_flattened_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = knowledge_base.KnowledgeBase() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(knowledge_base.KnowledgeBase()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_knowledge_base( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_knowledge_base_flattened_error_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_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_knowledge_base( + knowledge_base.GetKnowledgeBaseRequest(), + name='name_value', + ) + + +def test_create_knowledge_base(transport: str = 'grpc', request_type=gcd_knowledge_base.CreateKnowledgeBaseRequest): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_knowledge_base.KnowledgeBase( + name='name_value', + display_name='display_name_value', + language_code='language_code_value', + ) + response = client.create_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_knowledge_base.CreateKnowledgeBaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_knowledge_base.KnowledgeBase) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.language_code == 'language_code_value' + + +def test_create_knowledge_base_from_dict(): + test_create_knowledge_base(request_type=dict) + + +def test_create_knowledge_base_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = KnowledgeBasesClient( + credentials=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_knowledge_base), + '__call__') as call: + client.create_knowledge_base() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_knowledge_base.CreateKnowledgeBaseRequest() + + +@pytest.mark.asyncio +async def test_create_knowledge_base_async(transport: str = 'grpc_asyncio', request_type=gcd_knowledge_base.CreateKnowledgeBaseRequest): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_knowledge_base.KnowledgeBase( + name='name_value', + display_name='display_name_value', + language_code='language_code_value', + )) + response = await client.create_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_knowledge_base.CreateKnowledgeBaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_knowledge_base.KnowledgeBase) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_create_knowledge_base_async_from_dict(): + await test_create_knowledge_base_async(request_type=dict) + + +def test_create_knowledge_base_field_headers(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_knowledge_base.CreateKnowledgeBaseRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_knowledge_base), + '__call__') as call: + call.return_value = gcd_knowledge_base.KnowledgeBase() + client.create_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_knowledge_base_field_headers_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_knowledge_base.CreateKnowledgeBaseRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_knowledge_base), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_knowledge_base.KnowledgeBase()) + await client.create_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_knowledge_base_flattened(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_knowledge_base.KnowledgeBase() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_knowledge_base( + parent='parent_value', + knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].knowledge_base + mock_val = gcd_knowledge_base.KnowledgeBase(name='name_value') + assert arg == mock_val + + +def test_create_knowledge_base_flattened_error(): + client = KnowledgeBasesClient( + credentials=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_knowledge_base( + gcd_knowledge_base.CreateKnowledgeBaseRequest(), + parent='parent_value', + knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_knowledge_base_flattened_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_knowledge_base.KnowledgeBase() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_knowledge_base.KnowledgeBase()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_knowledge_base( + parent='parent_value', + knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].knowledge_base + mock_val = gcd_knowledge_base.KnowledgeBase(name='name_value') + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_knowledge_base_flattened_error_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_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_knowledge_base( + gcd_knowledge_base.CreateKnowledgeBaseRequest(), + parent='parent_value', + knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), + ) + + +def test_delete_knowledge_base(transport: str = 'grpc', request_type=knowledge_base.DeleteKnowledgeBaseRequest): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == knowledge_base.DeleteKnowledgeBaseRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_knowledge_base_from_dict(): + test_delete_knowledge_base(request_type=dict) + + +def test_delete_knowledge_base_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = KnowledgeBasesClient( + credentials=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_knowledge_base), + '__call__') as call: + client.delete_knowledge_base() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == knowledge_base.DeleteKnowledgeBaseRequest() + + +@pytest.mark.asyncio +async def test_delete_knowledge_base_async(transport: str = 'grpc_asyncio', request_type=knowledge_base.DeleteKnowledgeBaseRequest): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == knowledge_base.DeleteKnowledgeBaseRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_knowledge_base_async_from_dict(): + await test_delete_knowledge_base_async(request_type=dict) + + +def test_delete_knowledge_base_field_headers(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = knowledge_base.DeleteKnowledgeBaseRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_knowledge_base), + '__call__') as call: + call.return_value = None + client.delete_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_knowledge_base_field_headers_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = knowledge_base.DeleteKnowledgeBaseRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_knowledge_base), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_knowledge_base_flattened(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_knowledge_base), + '__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_knowledge_base( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_knowledge_base_flattened_error(): + client = KnowledgeBasesClient( + credentials=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_knowledge_base( + knowledge_base.DeleteKnowledgeBaseRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_knowledge_base_flattened_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_knowledge_base), + '__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_knowledge_base( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_knowledge_base_flattened_error_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_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_knowledge_base( + knowledge_base.DeleteKnowledgeBaseRequest(), + name='name_value', + ) + + +def test_update_knowledge_base(transport: str = 'grpc', request_type=gcd_knowledge_base.UpdateKnowledgeBaseRequest): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_knowledge_base.KnowledgeBase( + name='name_value', + display_name='display_name_value', + language_code='language_code_value', + ) + response = client.update_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_knowledge_base.UpdateKnowledgeBaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_knowledge_base.KnowledgeBase) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.language_code == 'language_code_value' + + +def test_update_knowledge_base_from_dict(): + test_update_knowledge_base(request_type=dict) + + +def test_update_knowledge_base_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = KnowledgeBasesClient( + credentials=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_knowledge_base), + '__call__') as call: + client.update_knowledge_base() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_knowledge_base.UpdateKnowledgeBaseRequest() + + +@pytest.mark.asyncio +async def test_update_knowledge_base_async(transport: str = 'grpc_asyncio', request_type=gcd_knowledge_base.UpdateKnowledgeBaseRequest): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_knowledge_base.KnowledgeBase( + name='name_value', + display_name='display_name_value', + language_code='language_code_value', + )) + response = await client.update_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_knowledge_base.UpdateKnowledgeBaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_knowledge_base.KnowledgeBase) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_update_knowledge_base_async_from_dict(): + await test_update_knowledge_base_async(request_type=dict) + + +def test_update_knowledge_base_field_headers(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_knowledge_base.UpdateKnowledgeBaseRequest() + + request.knowledge_base.name = 'knowledge_base.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_knowledge_base), + '__call__') as call: + call.return_value = gcd_knowledge_base.KnowledgeBase() + client.update_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'knowledge_base.name=knowledge_base.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_knowledge_base_field_headers_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_knowledge_base.UpdateKnowledgeBaseRequest() + + request.knowledge_base.name = 'knowledge_base.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_knowledge_base), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_knowledge_base.KnowledgeBase()) + await client.update_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'knowledge_base.name=knowledge_base.name/value', + ) in kw['metadata'] + + +def test_update_knowledge_base_flattened(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_knowledge_base.KnowledgeBase() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_knowledge_base( + knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].knowledge_base + mock_val = gcd_knowledge_base.KnowledgeBase(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_knowledge_base_flattened_error(): + client = KnowledgeBasesClient( + credentials=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_knowledge_base( + gcd_knowledge_base.UpdateKnowledgeBaseRequest(), + knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_knowledge_base_flattened_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_knowledge_base.KnowledgeBase() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_knowledge_base.KnowledgeBase()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_knowledge_base( + knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].knowledge_base + mock_val = gcd_knowledge_base.KnowledgeBase(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_knowledge_base_flattened_error_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_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_knowledge_base( + gcd_knowledge_base.UpdateKnowledgeBaseRequest(), + knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.KnowledgeBasesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.KnowledgeBasesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = KnowledgeBasesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.KnowledgeBasesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = KnowledgeBasesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.KnowledgeBasesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = KnowledgeBasesClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.KnowledgeBasesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.KnowledgeBasesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.KnowledgeBasesGrpcTransport, + transports.KnowledgeBasesGrpcAsyncIOTransport, +]) +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 = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.KnowledgeBasesGrpcTransport, + ) + +def test_knowledge_bases_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.KnowledgeBasesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_knowledge_bases_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2.services.knowledge_bases.transports.KnowledgeBasesTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.KnowledgeBasesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_knowledge_bases', + 'get_knowledge_base', + 'create_knowledge_base', + 'delete_knowledge_base', + 'update_knowledge_base', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_knowledge_bases_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.dialogflow_v2.services.knowledge_bases.transports.KnowledgeBasesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.KnowledgeBasesTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_knowledge_bases_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.dialogflow_v2.services.knowledge_bases.transports.KnowledgeBasesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.KnowledgeBasesTransport() + adc.assert_called_once() + + +def test_knowledge_bases_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) + KnowledgeBasesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.KnowledgeBasesGrpcTransport, + transports.KnowledgeBasesGrpcAsyncIOTransport, + ], +) +def test_knowledge_bases_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.KnowledgeBasesGrpcTransport, grpc_helpers), + (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_knowledge_bases_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.KnowledgeBasesGrpcTransport, transports.KnowledgeBasesGrpcAsyncIOTransport]) +def test_knowledge_bases_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_knowledge_bases_host_no_port(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_knowledge_bases_host_with_port(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_knowledge_bases_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.KnowledgeBasesGrpcTransport( + 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_knowledge_bases_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.KnowledgeBasesGrpcAsyncIOTransport( + 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.KnowledgeBasesGrpcTransport, transports.KnowledgeBasesGrpcAsyncIOTransport]) +def test_knowledge_bases_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.KnowledgeBasesGrpcTransport, transports.KnowledgeBasesGrpcAsyncIOTransport]) +def test_knowledge_bases_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_knowledge_base_path(): + project = "squid" + knowledge_base = "clam" + expected = "projects/{project}/knowledgeBases/{knowledge_base}".format(project=project, knowledge_base=knowledge_base, ) + actual = KnowledgeBasesClient.knowledge_base_path(project, knowledge_base) + assert expected == actual + + +def test_parse_knowledge_base_path(): + expected = { + "project": "whelk", + "knowledge_base": "octopus", + } + path = KnowledgeBasesClient.knowledge_base_path(**expected) + + # Check that the path construction is reversible. + actual = KnowledgeBasesClient.parse_knowledge_base_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = KnowledgeBasesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = KnowledgeBasesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = KnowledgeBasesClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = KnowledgeBasesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = KnowledgeBasesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = KnowledgeBasesClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = KnowledgeBasesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = KnowledgeBasesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = KnowledgeBasesClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = KnowledgeBasesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = KnowledgeBasesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = KnowledgeBasesClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = KnowledgeBasesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = KnowledgeBasesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = KnowledgeBasesClient.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.KnowledgeBasesTransport, '_prep_wrapped_messages') as prep: + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.KnowledgeBasesTransport, '_prep_wrapped_messages') as prep: + transport_class = KnowledgeBasesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_participants.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_participants.py new file mode 100644 index 000000000..3fff03358 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_participants.py @@ -0,0 +1,2908 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.participants import ParticipantsAsyncClient +from google.cloud.dialogflow_v2.services.participants import ParticipantsClient +from google.cloud.dialogflow_v2.services.participants import pagers +from google.cloud.dialogflow_v2.services.participants import transports +from google.cloud.dialogflow_v2.types import audio_config +from google.cloud.dialogflow_v2.types import context +from google.cloud.dialogflow_v2.types import entity_type +from google.cloud.dialogflow_v2.types import participant +from google.cloud.dialogflow_v2.types import participant as gcd_participant +from google.cloud.dialogflow_v2.types import session +from google.cloud.dialogflow_v2.types import session_entity_type +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ParticipantsClient._get_default_mtls_endpoint(None) is None + assert ParticipantsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ParticipantsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ParticipantsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ParticipantsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ParticipantsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + ParticipantsClient, + ParticipantsAsyncClient, +]) +def test_participants_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ParticipantsGrpcTransport, "grpc"), + (transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_participants_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + ParticipantsClient, + ParticipantsAsyncClient, +]) +def test_participants_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 == 'dialogflow.googleapis.com:443' + + +def test_participants_client_get_transport_class(): + transport = ParticipantsClient.get_transport_class() + available_transports = [ + transports.ParticipantsGrpcTransport, + ] + assert transport in available_transports + + transport = ParticipantsClient.get_transport_class("grpc") + assert transport == transports.ParticipantsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc"), + (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ParticipantsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ParticipantsClient)) +@mock.patch.object(ParticipantsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ParticipantsAsyncClient)) +def test_participants_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(ParticipantsClient, '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(ParticipantsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc", "true"), + (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc", "false"), + (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ParticipantsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ParticipantsClient)) +@mock.patch.object(ParticipantsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ParticipantsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_participants_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc"), + (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_participants_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc"), + (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_participants_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_participants_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2.services.participants.transports.ParticipantsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ParticipantsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_create_participant(transport: str = 'grpc', request_type=gcd_participant.CreateParticipantRequest): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_participant), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_participant.Participant( + name='name_value', + role=gcd_participant.Participant.Role.HUMAN_AGENT, + sip_recording_media_label='sip_recording_media_label_value', + ) + response = client.create_participant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_participant.CreateParticipantRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_participant.Participant) + assert response.name == 'name_value' + assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT + assert response.sip_recording_media_label == 'sip_recording_media_label_value' + + +def test_create_participant_from_dict(): + test_create_participant(request_type=dict) + + +def test_create_participant_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ParticipantsClient( + credentials=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_participant), + '__call__') as call: + client.create_participant() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_participant.CreateParticipantRequest() + + +@pytest.mark.asyncio +async def test_create_participant_async(transport: str = 'grpc_asyncio', request_type=gcd_participant.CreateParticipantRequest): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_participant), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.Participant( + name='name_value', + role=gcd_participant.Participant.Role.HUMAN_AGENT, + sip_recording_media_label='sip_recording_media_label_value', + )) + response = await client.create_participant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_participant.CreateParticipantRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_participant.Participant) + assert response.name == 'name_value' + assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT + assert response.sip_recording_media_label == 'sip_recording_media_label_value' + + +@pytest.mark.asyncio +async def test_create_participant_async_from_dict(): + await test_create_participant_async(request_type=dict) + + +def test_create_participant_field_headers(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_participant.CreateParticipantRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_participant), + '__call__') as call: + call.return_value = gcd_participant.Participant() + client.create_participant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_participant_field_headers_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_participant.CreateParticipantRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_participant), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.Participant()) + await client.create_participant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_participant_flattened(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_participant), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_participant.Participant() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_participant( + parent='parent_value', + participant=gcd_participant.Participant(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].participant + mock_val = gcd_participant.Participant(name='name_value') + assert arg == mock_val + + +def test_create_participant_flattened_error(): + client = ParticipantsClient( + credentials=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_participant( + gcd_participant.CreateParticipantRequest(), + parent='parent_value', + participant=gcd_participant.Participant(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_participant_flattened_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_participant), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_participant.Participant() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.Participant()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_participant( + parent='parent_value', + participant=gcd_participant.Participant(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].participant + mock_val = gcd_participant.Participant(name='name_value') + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_participant_flattened_error_async(): + client = ParticipantsAsyncClient( + credentials=ga_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_participant( + gcd_participant.CreateParticipantRequest(), + parent='parent_value', + participant=gcd_participant.Participant(name='name_value'), + ) + + +def test_get_participant(transport: str = 'grpc', request_type=participant.GetParticipantRequest): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_participant), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.Participant( + name='name_value', + role=participant.Participant.Role.HUMAN_AGENT, + sip_recording_media_label='sip_recording_media_label_value', + ) + response = client.get_participant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == participant.GetParticipantRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, participant.Participant) + assert response.name == 'name_value' + assert response.role == participant.Participant.Role.HUMAN_AGENT + assert response.sip_recording_media_label == 'sip_recording_media_label_value' + + +def test_get_participant_from_dict(): + test_get_participant(request_type=dict) + + +def test_get_participant_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ParticipantsClient( + credentials=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_participant), + '__call__') as call: + client.get_participant() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == participant.GetParticipantRequest() + + +@pytest.mark.asyncio +async def test_get_participant_async(transport: str = 'grpc_asyncio', request_type=participant.GetParticipantRequest): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_participant), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(participant.Participant( + name='name_value', + role=participant.Participant.Role.HUMAN_AGENT, + sip_recording_media_label='sip_recording_media_label_value', + )) + response = await client.get_participant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == participant.GetParticipantRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, participant.Participant) + assert response.name == 'name_value' + assert response.role == participant.Participant.Role.HUMAN_AGENT + assert response.sip_recording_media_label == 'sip_recording_media_label_value' + + +@pytest.mark.asyncio +async def test_get_participant_async_from_dict(): + await test_get_participant_async(request_type=dict) + + +def test_get_participant_field_headers(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = participant.GetParticipantRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_participant), + '__call__') as call: + call.return_value = participant.Participant() + client.get_participant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_participant_field_headers_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = participant.GetParticipantRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_participant), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.Participant()) + await client.get_participant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_participant_flattened(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_participant), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.Participant() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_participant( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_participant_flattened_error(): + client = ParticipantsClient( + credentials=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_participant( + participant.GetParticipantRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_participant_flattened_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_participant), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.Participant() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.Participant()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_participant( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_participant_flattened_error_async(): + client = ParticipantsAsyncClient( + credentials=ga_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_participant( + participant.GetParticipantRequest(), + name='name_value', + ) + + +def test_list_participants(transport: str = 'grpc', request_type=participant.ListParticipantsRequest): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_participants), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.ListParticipantsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_participants(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == participant.ListParticipantsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListParticipantsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_participants_from_dict(): + test_list_participants(request_type=dict) + + +def test_list_participants_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ParticipantsClient( + credentials=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_participants), + '__call__') as call: + client.list_participants() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == participant.ListParticipantsRequest() + + +@pytest.mark.asyncio +async def test_list_participants_async(transport: str = 'grpc_asyncio', request_type=participant.ListParticipantsRequest): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_participants), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(participant.ListParticipantsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_participants(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == participant.ListParticipantsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListParticipantsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_participants_async_from_dict(): + await test_list_participants_async(request_type=dict) + + +def test_list_participants_field_headers(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = participant.ListParticipantsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_participants), + '__call__') as call: + call.return_value = participant.ListParticipantsResponse() + client.list_participants(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_participants_field_headers_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = participant.ListParticipantsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_participants), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.ListParticipantsResponse()) + await client.list_participants(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_participants_flattened(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_participants), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.ListParticipantsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_participants( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_participants_flattened_error(): + client = ParticipantsClient( + credentials=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_participants( + participant.ListParticipantsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_participants_flattened_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_participants), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.ListParticipantsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.ListParticipantsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_participants( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_participants_flattened_error_async(): + client = ParticipantsAsyncClient( + credentials=ga_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_participants( + participant.ListParticipantsRequest(), + parent='parent_value', + ) + + +def test_list_participants_pager(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_participants), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + participant.ListParticipantsResponse( + participants=[ + participant.Participant(), + participant.Participant(), + participant.Participant(), + ], + next_page_token='abc', + ), + participant.ListParticipantsResponse( + participants=[], + next_page_token='def', + ), + participant.ListParticipantsResponse( + participants=[ + participant.Participant(), + ], + next_page_token='ghi', + ), + participant.ListParticipantsResponse( + participants=[ + participant.Participant(), + participant.Participant(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_participants(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, participant.Participant) + for i in results) + +def test_list_participants_pages(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_participants), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + participant.ListParticipantsResponse( + participants=[ + participant.Participant(), + participant.Participant(), + participant.Participant(), + ], + next_page_token='abc', + ), + participant.ListParticipantsResponse( + participants=[], + next_page_token='def', + ), + participant.ListParticipantsResponse( + participants=[ + participant.Participant(), + ], + next_page_token='ghi', + ), + participant.ListParticipantsResponse( + participants=[ + participant.Participant(), + participant.Participant(), + ], + ), + RuntimeError, + ) + pages = list(client.list_participants(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_participants_async_pager(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_participants), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + participant.ListParticipantsResponse( + participants=[ + participant.Participant(), + participant.Participant(), + participant.Participant(), + ], + next_page_token='abc', + ), + participant.ListParticipantsResponse( + participants=[], + next_page_token='def', + ), + participant.ListParticipantsResponse( + participants=[ + participant.Participant(), + ], + next_page_token='ghi', + ), + participant.ListParticipantsResponse( + participants=[ + participant.Participant(), + participant.Participant(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_participants(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, participant.Participant) + for i in responses) + +@pytest.mark.asyncio +async def test_list_participants_async_pages(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_participants), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + participant.ListParticipantsResponse( + participants=[ + participant.Participant(), + participant.Participant(), + participant.Participant(), + ], + next_page_token='abc', + ), + participant.ListParticipantsResponse( + participants=[], + next_page_token='def', + ), + participant.ListParticipantsResponse( + participants=[ + participant.Participant(), + ], + next_page_token='ghi', + ), + participant.ListParticipantsResponse( + participants=[ + participant.Participant(), + participant.Participant(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_participants(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_participant(transport: str = 'grpc', request_type=gcd_participant.UpdateParticipantRequest): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_participant), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_participant.Participant( + name='name_value', + role=gcd_participant.Participant.Role.HUMAN_AGENT, + sip_recording_media_label='sip_recording_media_label_value', + ) + response = client.update_participant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_participant.UpdateParticipantRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_participant.Participant) + assert response.name == 'name_value' + assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT + assert response.sip_recording_media_label == 'sip_recording_media_label_value' + + +def test_update_participant_from_dict(): + test_update_participant(request_type=dict) + + +def test_update_participant_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ParticipantsClient( + credentials=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_participant), + '__call__') as call: + client.update_participant() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_participant.UpdateParticipantRequest() + + +@pytest.mark.asyncio +async def test_update_participant_async(transport: str = 'grpc_asyncio', request_type=gcd_participant.UpdateParticipantRequest): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_participant), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.Participant( + name='name_value', + role=gcd_participant.Participant.Role.HUMAN_AGENT, + sip_recording_media_label='sip_recording_media_label_value', + )) + response = await client.update_participant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_participant.UpdateParticipantRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_participant.Participant) + assert response.name == 'name_value' + assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT + assert response.sip_recording_media_label == 'sip_recording_media_label_value' + + +@pytest.mark.asyncio +async def test_update_participant_async_from_dict(): + await test_update_participant_async(request_type=dict) + + +def test_update_participant_field_headers(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_participant.UpdateParticipantRequest() + + request.participant.name = 'participant.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_participant), + '__call__') as call: + call.return_value = gcd_participant.Participant() + client.update_participant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'participant.name=participant.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_participant_field_headers_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_participant.UpdateParticipantRequest() + + request.participant.name = 'participant.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_participant), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.Participant()) + await client.update_participant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'participant.name=participant.name/value', + ) in kw['metadata'] + + +def test_update_participant_flattened(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_participant), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_participant.Participant() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_participant( + participant=gcd_participant.Participant(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].participant + mock_val = gcd_participant.Participant(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_participant_flattened_error(): + client = ParticipantsClient( + credentials=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_participant( + gcd_participant.UpdateParticipantRequest(), + participant=gcd_participant.Participant(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_participant_flattened_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_participant), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_participant.Participant() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.Participant()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_participant( + participant=gcd_participant.Participant(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].participant + mock_val = gcd_participant.Participant(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_participant_flattened_error_async(): + client = ParticipantsAsyncClient( + credentials=ga_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_participant( + gcd_participant.UpdateParticipantRequest(), + participant=gcd_participant.Participant(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_analyze_content(transport: str = 'grpc', request_type=gcd_participant.AnalyzeContentRequest): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_content), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_participant.AnalyzeContentResponse( + reply_text='reply_text_value', + ) + response = client.analyze_content(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_participant.AnalyzeContentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_participant.AnalyzeContentResponse) + assert response.reply_text == 'reply_text_value' + + +def test_analyze_content_from_dict(): + test_analyze_content(request_type=dict) + + +def test_analyze_content_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_content), + '__call__') as call: + client.analyze_content() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_participant.AnalyzeContentRequest() + + +@pytest.mark.asyncio +async def test_analyze_content_async(transport: str = 'grpc_asyncio', request_type=gcd_participant.AnalyzeContentRequest): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_content), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.AnalyzeContentResponse( + reply_text='reply_text_value', + )) + response = await client.analyze_content(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_participant.AnalyzeContentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_participant.AnalyzeContentResponse) + assert response.reply_text == 'reply_text_value' + + +@pytest.mark.asyncio +async def test_analyze_content_async_from_dict(): + await test_analyze_content_async(request_type=dict) + + +def test_analyze_content_field_headers(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_participant.AnalyzeContentRequest() + + request.participant = 'participant/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_content), + '__call__') as call: + call.return_value = gcd_participant.AnalyzeContentResponse() + client.analyze_content(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'participant=participant/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_analyze_content_field_headers_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_participant.AnalyzeContentRequest() + + request.participant = 'participant/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_content), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.AnalyzeContentResponse()) + await client.analyze_content(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'participant=participant/value', + ) in kw['metadata'] + + +def test_analyze_content_flattened(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_content), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_participant.AnalyzeContentResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.analyze_content( + participant='participant_value', + text_input=session.TextInput(text='text_value'), + event_input=session.EventInput(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].participant + mock_val = 'participant_value' + assert arg == mock_val + assert args[0].event_input == session.EventInput(name='name_value') + + +def test_analyze_content_flattened_error(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.analyze_content( + gcd_participant.AnalyzeContentRequest(), + participant='participant_value', + text_input=session.TextInput(text='text_value'), + event_input=session.EventInput(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_analyze_content_flattened_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_content), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_participant.AnalyzeContentResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.AnalyzeContentResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.analyze_content( + participant='participant_value', + text_input=session.TextInput(text='text_value'), + event_input=session.EventInput(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].participant + mock_val = 'participant_value' + assert arg == mock_val + assert args[0].event_input == session.EventInput(name='name_value') + + +@pytest.mark.asyncio +async def test_analyze_content_flattened_error_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.analyze_content( + gcd_participant.AnalyzeContentRequest(), + participant='participant_value', + text_input=session.TextInput(text='text_value'), + event_input=session.EventInput(name='name_value'), + ) + + +def test_suggest_articles(transport: str = 'grpc', request_type=participant.SuggestArticlesRequest): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_articles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.SuggestArticlesResponse( + latest_message='latest_message_value', + context_size=1311, + ) + response = client.suggest_articles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == participant.SuggestArticlesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, participant.SuggestArticlesResponse) + assert response.latest_message == 'latest_message_value' + assert response.context_size == 1311 + + +def test_suggest_articles_from_dict(): + test_suggest_articles(request_type=dict) + + +def test_suggest_articles_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_articles), + '__call__') as call: + client.suggest_articles() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == participant.SuggestArticlesRequest() + + +@pytest.mark.asyncio +async def test_suggest_articles_async(transport: str = 'grpc_asyncio', request_type=participant.SuggestArticlesRequest): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_articles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestArticlesResponse( + latest_message='latest_message_value', + context_size=1311, + )) + response = await client.suggest_articles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == participant.SuggestArticlesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, participant.SuggestArticlesResponse) + assert response.latest_message == 'latest_message_value' + assert response.context_size == 1311 + + +@pytest.mark.asyncio +async def test_suggest_articles_async_from_dict(): + await test_suggest_articles_async(request_type=dict) + + +def test_suggest_articles_field_headers(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = participant.SuggestArticlesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_articles), + '__call__') as call: + call.return_value = participant.SuggestArticlesResponse() + client.suggest_articles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_suggest_articles_field_headers_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = participant.SuggestArticlesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_articles), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestArticlesResponse()) + await client.suggest_articles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_suggest_articles_flattened(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_articles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.SuggestArticlesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.suggest_articles( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_suggest_articles_flattened_error(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.suggest_articles( + participant.SuggestArticlesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_suggest_articles_flattened_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_articles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.SuggestArticlesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestArticlesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.suggest_articles( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_suggest_articles_flattened_error_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.suggest_articles( + participant.SuggestArticlesRequest(), + parent='parent_value', + ) + + +def test_suggest_faq_answers(transport: str = 'grpc', request_type=participant.SuggestFaqAnswersRequest): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_faq_answers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.SuggestFaqAnswersResponse( + latest_message='latest_message_value', + context_size=1311, + ) + response = client.suggest_faq_answers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == participant.SuggestFaqAnswersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, participant.SuggestFaqAnswersResponse) + assert response.latest_message == 'latest_message_value' + assert response.context_size == 1311 + + +def test_suggest_faq_answers_from_dict(): + test_suggest_faq_answers(request_type=dict) + + +def test_suggest_faq_answers_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_faq_answers), + '__call__') as call: + client.suggest_faq_answers() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == participant.SuggestFaqAnswersRequest() + + +@pytest.mark.asyncio +async def test_suggest_faq_answers_async(transport: str = 'grpc_asyncio', request_type=participant.SuggestFaqAnswersRequest): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_faq_answers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestFaqAnswersResponse( + latest_message='latest_message_value', + context_size=1311, + )) + response = await client.suggest_faq_answers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == participant.SuggestFaqAnswersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, participant.SuggestFaqAnswersResponse) + assert response.latest_message == 'latest_message_value' + assert response.context_size == 1311 + + +@pytest.mark.asyncio +async def test_suggest_faq_answers_async_from_dict(): + await test_suggest_faq_answers_async(request_type=dict) + + +def test_suggest_faq_answers_field_headers(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = participant.SuggestFaqAnswersRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_faq_answers), + '__call__') as call: + call.return_value = participant.SuggestFaqAnswersResponse() + client.suggest_faq_answers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_suggest_faq_answers_field_headers_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = participant.SuggestFaqAnswersRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_faq_answers), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestFaqAnswersResponse()) + await client.suggest_faq_answers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_suggest_faq_answers_flattened(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_faq_answers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.SuggestFaqAnswersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.suggest_faq_answers( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_suggest_faq_answers_flattened_error(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.suggest_faq_answers( + participant.SuggestFaqAnswersRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_suggest_faq_answers_flattened_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_faq_answers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.SuggestFaqAnswersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestFaqAnswersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.suggest_faq_answers( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_suggest_faq_answers_flattened_error_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.suggest_faq_answers( + participant.SuggestFaqAnswersRequest(), + parent='parent_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ParticipantsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ParticipantsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ParticipantsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ParticipantsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ParticipantsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ParticipantsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ParticipantsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ParticipantsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ParticipantsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ParticipantsGrpcTransport, + transports.ParticipantsGrpcAsyncIOTransport, +]) +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 = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ParticipantsGrpcTransport, + ) + +def test_participants_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ParticipantsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_participants_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2.services.participants.transports.ParticipantsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ParticipantsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_participant', + 'get_participant', + 'list_participants', + 'update_participant', + 'analyze_content', + 'suggest_articles', + 'suggest_faq_answers', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_participants_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.dialogflow_v2.services.participants.transports.ParticipantsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ParticipantsTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_participants_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.dialogflow_v2.services.participants.transports.ParticipantsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ParticipantsTransport() + adc.assert_called_once() + + +def test_participants_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) + ParticipantsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ParticipantsGrpcTransport, + transports.ParticipantsGrpcAsyncIOTransport, + ], +) +def test_participants_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ParticipantsGrpcTransport, grpc_helpers), + (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_participants_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ParticipantsGrpcTransport, transports.ParticipantsGrpcAsyncIOTransport]) +def test_participants_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_participants_host_no_port(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_participants_host_with_port(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_participants_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ParticipantsGrpcTransport( + 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_participants_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ParticipantsGrpcAsyncIOTransport( + 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.ParticipantsGrpcTransport, transports.ParticipantsGrpcAsyncIOTransport]) +def test_participants_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.ParticipantsGrpcTransport, transports.ParticipantsGrpcAsyncIOTransport]) +def test_participants_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_context_path(): + project = "squid" + session = "clam" + context = "whelk" + expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) + actual = ParticipantsClient.context_path(project, session, context) + assert expected == actual + + +def test_parse_context_path(): + expected = { + "project": "octopus", + "session": "oyster", + "context": "nudibranch", + } + path = ParticipantsClient.context_path(**expected) + + # Check that the path construction is reversible. + actual = ParticipantsClient.parse_context_path(path) + assert expected == actual + +def test_intent_path(): + project = "cuttlefish" + intent = "mussel" + expected = "projects/{project}/agent/intents/{intent}".format(project=project, intent=intent, ) + actual = ParticipantsClient.intent_path(project, intent) + assert expected == actual + + +def test_parse_intent_path(): + expected = { + "project": "winkle", + "intent": "nautilus", + } + path = ParticipantsClient.intent_path(**expected) + + # Check that the path construction is reversible. + actual = ParticipantsClient.parse_intent_path(path) + assert expected == actual + +def test_message_path(): + project = "scallop" + conversation = "abalone" + message = "squid" + expected = "projects/{project}/conversations/{conversation}/messages/{message}".format(project=project, conversation=conversation, message=message, ) + actual = ParticipantsClient.message_path(project, conversation, message) + assert expected == actual + + +def test_parse_message_path(): + expected = { + "project": "clam", + "conversation": "whelk", + "message": "octopus", + } + path = ParticipantsClient.message_path(**expected) + + # Check that the path construction is reversible. + actual = ParticipantsClient.parse_message_path(path) + assert expected == actual + +def test_participant_path(): + project = "oyster" + conversation = "nudibranch" + participant = "cuttlefish" + expected = "projects/{project}/conversations/{conversation}/participants/{participant}".format(project=project, conversation=conversation, participant=participant, ) + actual = ParticipantsClient.participant_path(project, conversation, participant) + assert expected == actual + + +def test_parse_participant_path(): + expected = { + "project": "mussel", + "conversation": "winkle", + "participant": "nautilus", + } + path = ParticipantsClient.participant_path(**expected) + + # Check that the path construction is reversible. + actual = ParticipantsClient.parse_participant_path(path) + assert expected == actual + +def test_session_entity_type_path(): + project = "scallop" + session = "abalone" + entity_type = "squid" + expected = "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format(project=project, session=session, entity_type=entity_type, ) + actual = ParticipantsClient.session_entity_type_path(project, session, entity_type) + assert expected == actual + + +def test_parse_session_entity_type_path(): + expected = { + "project": "clam", + "session": "whelk", + "entity_type": "octopus", + } + path = ParticipantsClient.session_entity_type_path(**expected) + + # Check that the path construction is reversible. + actual = ParticipantsClient.parse_session_entity_type_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ParticipantsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = ParticipantsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ParticipantsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = ParticipantsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = ParticipantsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ParticipantsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ParticipantsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = ParticipantsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ParticipantsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = ParticipantsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = ParticipantsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ParticipantsClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ParticipantsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = ParticipantsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ParticipantsClient.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.ParticipantsTransport, '_prep_wrapped_messages') as prep: + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ParticipantsTransport, '_prep_wrapped_messages') as prep: + transport_class = ParticipantsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_session_entity_types.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_session_entity_types.py new file mode 100644 index 000000000..3cdac53f2 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_session_entity_types.py @@ -0,0 +1,2312 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.session_entity_types import SessionEntityTypesAsyncClient +from google.cloud.dialogflow_v2.services.session_entity_types import SessionEntityTypesClient +from google.cloud.dialogflow_v2.services.session_entity_types import pagers +from google.cloud.dialogflow_v2.services.session_entity_types import transports +from google.cloud.dialogflow_v2.types import entity_type +from google.cloud.dialogflow_v2.types import session_entity_type +from google.cloud.dialogflow_v2.types import session_entity_type as gcd_session_entity_type +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SessionEntityTypesClient._get_default_mtls_endpoint(None) is None + assert SessionEntityTypesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SessionEntityTypesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SessionEntityTypesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SessionEntityTypesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SessionEntityTypesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + SessionEntityTypesClient, + SessionEntityTypesAsyncClient, +]) +def test_session_entity_types_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SessionEntityTypesGrpcTransport, "grpc"), + (transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_session_entity_types_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + SessionEntityTypesClient, + SessionEntityTypesAsyncClient, +]) +def test_session_entity_types_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 == 'dialogflow.googleapis.com:443' + + +def test_session_entity_types_client_get_transport_class(): + transport = SessionEntityTypesClient.get_transport_class() + available_transports = [ + transports.SessionEntityTypesGrpcTransport, + ] + assert transport in available_transports + + transport = SessionEntityTypesClient.get_transport_class("grpc") + assert transport == transports.SessionEntityTypesGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc"), + (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(SessionEntityTypesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionEntityTypesClient)) +@mock.patch.object(SessionEntityTypesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionEntityTypesAsyncClient)) +def test_session_entity_types_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(SessionEntityTypesClient, '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(SessionEntityTypesClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc", "true"), + (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc", "false"), + (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(SessionEntityTypesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionEntityTypesClient)) +@mock.patch.object(SessionEntityTypesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionEntityTypesAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_session_entity_types_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc"), + (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_session_entity_types_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc"), + (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_session_entity_types_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_session_entity_types_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2.services.session_entity_types.transports.SessionEntityTypesGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SessionEntityTypesClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_session_entity_types(transport: str = 'grpc', request_type=session_entity_type.ListSessionEntityTypesRequest): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_session_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = session_entity_type.ListSessionEntityTypesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_session_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == session_entity_type.ListSessionEntityTypesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSessionEntityTypesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_session_entity_types_from_dict(): + test_list_session_entity_types(request_type=dict) + + +def test_list_session_entity_types_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SessionEntityTypesClient( + credentials=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_session_entity_types), + '__call__') as call: + client.list_session_entity_types() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == session_entity_type.ListSessionEntityTypesRequest() + + +@pytest.mark.asyncio +async def test_list_session_entity_types_async(transport: str = 'grpc_asyncio', request_type=session_entity_type.ListSessionEntityTypesRequest): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_session_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(session_entity_type.ListSessionEntityTypesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_session_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == session_entity_type.ListSessionEntityTypesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSessionEntityTypesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_session_entity_types_async_from_dict(): + await test_list_session_entity_types_async(request_type=dict) + + +def test_list_session_entity_types_field_headers(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = session_entity_type.ListSessionEntityTypesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_session_entity_types), + '__call__') as call: + call.return_value = session_entity_type.ListSessionEntityTypesResponse() + client.list_session_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_session_entity_types_field_headers_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = session_entity_type.ListSessionEntityTypesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_session_entity_types), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(session_entity_type.ListSessionEntityTypesResponse()) + await client.list_session_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_session_entity_types_flattened(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_session_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = session_entity_type.ListSessionEntityTypesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_session_entity_types( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_session_entity_types_flattened_error(): + client = SessionEntityTypesClient( + credentials=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_session_entity_types( + session_entity_type.ListSessionEntityTypesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_session_entity_types_flattened_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_session_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = session_entity_type.ListSessionEntityTypesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(session_entity_type.ListSessionEntityTypesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_session_entity_types( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_session_entity_types_flattened_error_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_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_session_entity_types( + session_entity_type.ListSessionEntityTypesRequest(), + parent='parent_value', + ) + + +def test_list_session_entity_types_pager(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_session_entity_types), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[ + session_entity_type.SessionEntityType(), + session_entity_type.SessionEntityType(), + session_entity_type.SessionEntityType(), + ], + next_page_token='abc', + ), + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[], + next_page_token='def', + ), + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[ + session_entity_type.SessionEntityType(), + ], + next_page_token='ghi', + ), + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[ + session_entity_type.SessionEntityType(), + session_entity_type.SessionEntityType(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_session_entity_types(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, session_entity_type.SessionEntityType) + for i in results) + +def test_list_session_entity_types_pages(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_session_entity_types), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[ + session_entity_type.SessionEntityType(), + session_entity_type.SessionEntityType(), + session_entity_type.SessionEntityType(), + ], + next_page_token='abc', + ), + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[], + next_page_token='def', + ), + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[ + session_entity_type.SessionEntityType(), + ], + next_page_token='ghi', + ), + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[ + session_entity_type.SessionEntityType(), + session_entity_type.SessionEntityType(), + ], + ), + RuntimeError, + ) + pages = list(client.list_session_entity_types(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_session_entity_types_async_pager(): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_session_entity_types), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[ + session_entity_type.SessionEntityType(), + session_entity_type.SessionEntityType(), + session_entity_type.SessionEntityType(), + ], + next_page_token='abc', + ), + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[], + next_page_token='def', + ), + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[ + session_entity_type.SessionEntityType(), + ], + next_page_token='ghi', + ), + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[ + session_entity_type.SessionEntityType(), + session_entity_type.SessionEntityType(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_session_entity_types(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, session_entity_type.SessionEntityType) + for i in responses) + +@pytest.mark.asyncio +async def test_list_session_entity_types_async_pages(): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_session_entity_types), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[ + session_entity_type.SessionEntityType(), + session_entity_type.SessionEntityType(), + session_entity_type.SessionEntityType(), + ], + next_page_token='abc', + ), + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[], + next_page_token='def', + ), + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[ + session_entity_type.SessionEntityType(), + ], + next_page_token='ghi', + ), + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[ + session_entity_type.SessionEntityType(), + session_entity_type.SessionEntityType(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_session_entity_types(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_session_entity_type(transport: str = 'grpc', request_type=session_entity_type.GetSessionEntityTypeRequest): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = session_entity_type.SessionEntityType( + name='name_value', + entity_override_mode=session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, + ) + response = client.get_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == session_entity_type.GetSessionEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, session_entity_type.SessionEntityType) + assert response.name == 'name_value' + assert response.entity_override_mode == session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE + + +def test_get_session_entity_type_from_dict(): + test_get_session_entity_type(request_type=dict) + + +def test_get_session_entity_type_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SessionEntityTypesClient( + credentials=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_session_entity_type), + '__call__') as call: + client.get_session_entity_type() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == session_entity_type.GetSessionEntityTypeRequest() + + +@pytest.mark.asyncio +async def test_get_session_entity_type_async(transport: str = 'grpc_asyncio', request_type=session_entity_type.GetSessionEntityTypeRequest): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(session_entity_type.SessionEntityType( + name='name_value', + entity_override_mode=session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, + )) + response = await client.get_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == session_entity_type.GetSessionEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, session_entity_type.SessionEntityType) + assert response.name == 'name_value' + assert response.entity_override_mode == session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE + + +@pytest.mark.asyncio +async def test_get_session_entity_type_async_from_dict(): + await test_get_session_entity_type_async(request_type=dict) + + +def test_get_session_entity_type_field_headers(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = session_entity_type.GetSessionEntityTypeRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_session_entity_type), + '__call__') as call: + call.return_value = session_entity_type.SessionEntityType() + client.get_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_session_entity_type_field_headers_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = session_entity_type.GetSessionEntityTypeRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_session_entity_type), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(session_entity_type.SessionEntityType()) + await client.get_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_session_entity_type_flattened(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = session_entity_type.SessionEntityType() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_session_entity_type( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_session_entity_type_flattened_error(): + client = SessionEntityTypesClient( + credentials=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_session_entity_type( + session_entity_type.GetSessionEntityTypeRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_session_entity_type_flattened_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = session_entity_type.SessionEntityType() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(session_entity_type.SessionEntityType()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_session_entity_type( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_session_entity_type_flattened_error_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_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_session_entity_type( + session_entity_type.GetSessionEntityTypeRequest(), + name='name_value', + ) + + +def test_create_session_entity_type(transport: str = 'grpc', request_type=gcd_session_entity_type.CreateSessionEntityTypeRequest): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_session_entity_type.SessionEntityType( + name='name_value', + entity_override_mode=gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, + ) + response = client.create_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_session_entity_type.CreateSessionEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_session_entity_type.SessionEntityType) + assert response.name == 'name_value' + assert response.entity_override_mode == gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE + + +def test_create_session_entity_type_from_dict(): + test_create_session_entity_type(request_type=dict) + + +def test_create_session_entity_type_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SessionEntityTypesClient( + credentials=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_session_entity_type), + '__call__') as call: + client.create_session_entity_type() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_session_entity_type.CreateSessionEntityTypeRequest() + + +@pytest.mark.asyncio +async def test_create_session_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcd_session_entity_type.CreateSessionEntityTypeRequest): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_session_entity_type.SessionEntityType( + name='name_value', + entity_override_mode=gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, + )) + response = await client.create_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_session_entity_type.CreateSessionEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_session_entity_type.SessionEntityType) + assert response.name == 'name_value' + assert response.entity_override_mode == gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE + + +@pytest.mark.asyncio +async def test_create_session_entity_type_async_from_dict(): + await test_create_session_entity_type_async(request_type=dict) + + +def test_create_session_entity_type_field_headers(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_session_entity_type.CreateSessionEntityTypeRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_session_entity_type), + '__call__') as call: + call.return_value = gcd_session_entity_type.SessionEntityType() + client.create_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_session_entity_type_field_headers_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_session_entity_type.CreateSessionEntityTypeRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_session_entity_type), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_session_entity_type.SessionEntityType()) + await client.create_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_session_entity_type_flattened(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_session_entity_type.SessionEntityType() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_session_entity_type( + parent='parent_value', + session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].session_entity_type + mock_val = gcd_session_entity_type.SessionEntityType(name='name_value') + assert arg == mock_val + + +def test_create_session_entity_type_flattened_error(): + client = SessionEntityTypesClient( + credentials=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_session_entity_type( + gcd_session_entity_type.CreateSessionEntityTypeRequest(), + parent='parent_value', + session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_session_entity_type_flattened_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_session_entity_type.SessionEntityType() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_session_entity_type.SessionEntityType()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_session_entity_type( + parent='parent_value', + session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].session_entity_type + mock_val = gcd_session_entity_type.SessionEntityType(name='name_value') + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_session_entity_type_flattened_error_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_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_session_entity_type( + gcd_session_entity_type.CreateSessionEntityTypeRequest(), + parent='parent_value', + session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), + ) + + +def test_update_session_entity_type(transport: str = 'grpc', request_type=gcd_session_entity_type.UpdateSessionEntityTypeRequest): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_session_entity_type.SessionEntityType( + name='name_value', + entity_override_mode=gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, + ) + response = client.update_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_session_entity_type.UpdateSessionEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_session_entity_type.SessionEntityType) + assert response.name == 'name_value' + assert response.entity_override_mode == gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE + + +def test_update_session_entity_type_from_dict(): + test_update_session_entity_type(request_type=dict) + + +def test_update_session_entity_type_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SessionEntityTypesClient( + credentials=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_session_entity_type), + '__call__') as call: + client.update_session_entity_type() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_session_entity_type.UpdateSessionEntityTypeRequest() + + +@pytest.mark.asyncio +async def test_update_session_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcd_session_entity_type.UpdateSessionEntityTypeRequest): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_session_entity_type.SessionEntityType( + name='name_value', + entity_override_mode=gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, + )) + response = await client.update_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_session_entity_type.UpdateSessionEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_session_entity_type.SessionEntityType) + assert response.name == 'name_value' + assert response.entity_override_mode == gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE + + +@pytest.mark.asyncio +async def test_update_session_entity_type_async_from_dict(): + await test_update_session_entity_type_async(request_type=dict) + + +def test_update_session_entity_type_field_headers(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_session_entity_type.UpdateSessionEntityTypeRequest() + + request.session_entity_type.name = 'session_entity_type.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_session_entity_type), + '__call__') as call: + call.return_value = gcd_session_entity_type.SessionEntityType() + client.update_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'session_entity_type.name=session_entity_type.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_session_entity_type_field_headers_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_session_entity_type.UpdateSessionEntityTypeRequest() + + request.session_entity_type.name = 'session_entity_type.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_session_entity_type), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_session_entity_type.SessionEntityType()) + await client.update_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'session_entity_type.name=session_entity_type.name/value', + ) in kw['metadata'] + + +def test_update_session_entity_type_flattened(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_session_entity_type.SessionEntityType() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_session_entity_type( + session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].session_entity_type + mock_val = gcd_session_entity_type.SessionEntityType(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_session_entity_type_flattened_error(): + client = SessionEntityTypesClient( + credentials=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_session_entity_type( + gcd_session_entity_type.UpdateSessionEntityTypeRequest(), + session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_session_entity_type_flattened_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_session_entity_type.SessionEntityType() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_session_entity_type.SessionEntityType()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_session_entity_type( + session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].session_entity_type + mock_val = gcd_session_entity_type.SessionEntityType(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_session_entity_type_flattened_error_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_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_session_entity_type( + gcd_session_entity_type.UpdateSessionEntityTypeRequest(), + session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_session_entity_type(transport: str = 'grpc', request_type=session_entity_type.DeleteSessionEntityTypeRequest): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == session_entity_type.DeleteSessionEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_session_entity_type_from_dict(): + test_delete_session_entity_type(request_type=dict) + + +def test_delete_session_entity_type_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SessionEntityTypesClient( + credentials=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_session_entity_type), + '__call__') as call: + client.delete_session_entity_type() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == session_entity_type.DeleteSessionEntityTypeRequest() + + +@pytest.mark.asyncio +async def test_delete_session_entity_type_async(transport: str = 'grpc_asyncio', request_type=session_entity_type.DeleteSessionEntityTypeRequest): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == session_entity_type.DeleteSessionEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_session_entity_type_async_from_dict(): + await test_delete_session_entity_type_async(request_type=dict) + + +def test_delete_session_entity_type_field_headers(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = session_entity_type.DeleteSessionEntityTypeRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_session_entity_type), + '__call__') as call: + call.return_value = None + client.delete_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_session_entity_type_field_headers_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = session_entity_type.DeleteSessionEntityTypeRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_session_entity_type), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_session_entity_type_flattened(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_session_entity_type), + '__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_session_entity_type( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_session_entity_type_flattened_error(): + client = SessionEntityTypesClient( + credentials=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_session_entity_type( + session_entity_type.DeleteSessionEntityTypeRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_session_entity_type_flattened_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_session_entity_type), + '__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_session_entity_type( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_session_entity_type_flattened_error_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_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_session_entity_type( + session_entity_type.DeleteSessionEntityTypeRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SessionEntityTypesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SessionEntityTypesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SessionEntityTypesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SessionEntityTypesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SessionEntityTypesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SessionEntityTypesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SessionEntityTypesClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SessionEntityTypesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SessionEntityTypesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SessionEntityTypesGrpcTransport, + transports.SessionEntityTypesGrpcAsyncIOTransport, +]) +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 = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SessionEntityTypesGrpcTransport, + ) + +def test_session_entity_types_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SessionEntityTypesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_session_entity_types_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2.services.session_entity_types.transports.SessionEntityTypesTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SessionEntityTypesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_session_entity_types', + 'get_session_entity_type', + 'create_session_entity_type', + 'update_session_entity_type', + 'delete_session_entity_type', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_session_entity_types_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.dialogflow_v2.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SessionEntityTypesTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_session_entity_types_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.dialogflow_v2.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SessionEntityTypesTransport() + adc.assert_called_once() + + +def test_session_entity_types_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) + SessionEntityTypesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SessionEntityTypesGrpcTransport, + transports.SessionEntityTypesGrpcAsyncIOTransport, + ], +) +def test_session_entity_types_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionEntityTypesGrpcTransport, grpc_helpers), + (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_session_entity_types_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SessionEntityTypesGrpcTransport, transports.SessionEntityTypesGrpcAsyncIOTransport]) +def test_session_entity_types_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_session_entity_types_host_no_port(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_session_entity_types_host_with_port(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_session_entity_types_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SessionEntityTypesGrpcTransport( + 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_session_entity_types_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SessionEntityTypesGrpcAsyncIOTransport( + 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.SessionEntityTypesGrpcTransport, transports.SessionEntityTypesGrpcAsyncIOTransport]) +def test_session_entity_types_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.SessionEntityTypesGrpcTransport, transports.SessionEntityTypesGrpcAsyncIOTransport]) +def test_session_entity_types_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_session_entity_type_path(): + project = "squid" + session = "clam" + entity_type = "whelk" + expected = "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format(project=project, session=session, entity_type=entity_type, ) + actual = SessionEntityTypesClient.session_entity_type_path(project, session, entity_type) + assert expected == actual + + +def test_parse_session_entity_type_path(): + expected = { + "project": "octopus", + "session": "oyster", + "entity_type": "nudibranch", + } + path = SessionEntityTypesClient.session_entity_type_path(**expected) + + # Check that the path construction is reversible. + actual = SessionEntityTypesClient.parse_session_entity_type_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SessionEntityTypesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = SessionEntityTypesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SessionEntityTypesClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = SessionEntityTypesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = SessionEntityTypesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SessionEntityTypesClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SessionEntityTypesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = SessionEntityTypesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SessionEntityTypesClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = SessionEntityTypesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = SessionEntityTypesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SessionEntityTypesClient.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 = SessionEntityTypesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = SessionEntityTypesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SessionEntityTypesClient.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.SessionEntityTypesTransport, '_prep_wrapped_messages') as prep: + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SessionEntityTypesTransport, '_prep_wrapped_messages') as prep: + transport_class = SessionEntityTypesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_sessions.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_sessions.py new file mode 100644 index 000000000..894526778 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_sessions.py @@ -0,0 +1,1304 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.sessions import SessionsAsyncClient +from google.cloud.dialogflow_v2.services.sessions import SessionsClient +from google.cloud.dialogflow_v2.services.sessions import transports +from google.cloud.dialogflow_v2.types import audio_config +from google.cloud.dialogflow_v2.types import context +from google.cloud.dialogflow_v2.types import entity_type +from google.cloud.dialogflow_v2.types import session +from google.cloud.dialogflow_v2.types import session as gcd_session +from google.cloud.dialogflow_v2.types import session_entity_type +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SessionsClient._get_default_mtls_endpoint(None) is None + assert SessionsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SessionsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SessionsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SessionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SessionsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + SessionsClient, + SessionsAsyncClient, +]) +def test_sessions_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SessionsGrpcTransport, "grpc"), + (transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_sessions_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + SessionsClient, + SessionsAsyncClient, +]) +def test_sessions_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 == 'dialogflow.googleapis.com:443' + + +def test_sessions_client_get_transport_class(): + transport = SessionsClient.get_transport_class() + available_transports = [ + transports.SessionsGrpcTransport, + ] + assert transport in available_transports + + transport = SessionsClient.get_transport_class("grpc") + assert transport == transports.SessionsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SessionsClient, transports.SessionsGrpcTransport, "grpc"), + (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(SessionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionsClient)) +@mock.patch.object(SessionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionsAsyncClient)) +def test_sessions_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(SessionsClient, '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(SessionsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (SessionsClient, transports.SessionsGrpcTransport, "grpc", "true"), + (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SessionsClient, transports.SessionsGrpcTransport, "grpc", "false"), + (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(SessionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionsClient)) +@mock.patch.object(SessionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_sessions_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SessionsClient, transports.SessionsGrpcTransport, "grpc"), + (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_sessions_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SessionsClient, transports.SessionsGrpcTransport, "grpc"), + (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_sessions_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_sessions_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2.services.sessions.transports.SessionsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SessionsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_detect_intent(transport: str = 'grpc', request_type=gcd_session.DetectIntentRequest): + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.detect_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_session.DetectIntentResponse( + response_id='response_id_value', + output_audio=b'output_audio_blob', + ) + response = client.detect_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_session.DetectIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_session.DetectIntentResponse) + assert response.response_id == 'response_id_value' + assert response.output_audio == b'output_audio_blob' + + +def test_detect_intent_from_dict(): + test_detect_intent(request_type=dict) + + +def test_detect_intent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.detect_intent), + '__call__') as call: + client.detect_intent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_session.DetectIntentRequest() + + +@pytest.mark.asyncio +async def test_detect_intent_async(transport: str = 'grpc_asyncio', request_type=gcd_session.DetectIntentRequest): + client = SessionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.detect_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_session.DetectIntentResponse( + response_id='response_id_value', + output_audio=b'output_audio_blob', + )) + response = await client.detect_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_session.DetectIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_session.DetectIntentResponse) + assert response.response_id == 'response_id_value' + assert response.output_audio == b'output_audio_blob' + + +@pytest.mark.asyncio +async def test_detect_intent_async_from_dict(): + await test_detect_intent_async(request_type=dict) + + +def test_detect_intent_field_headers(): + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_session.DetectIntentRequest() + + request.session = 'session/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.detect_intent), + '__call__') as call: + call.return_value = gcd_session.DetectIntentResponse() + client.detect_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'session=session/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_detect_intent_field_headers_async(): + client = SessionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_session.DetectIntentRequest() + + request.session = 'session/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.detect_intent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_session.DetectIntentResponse()) + await client.detect_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'session=session/value', + ) in kw['metadata'] + + +def test_detect_intent_flattened(): + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.detect_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_session.DetectIntentResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.detect_intent( + session='session_value', + query_input=gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].session + mock_val = 'session_value' + assert arg == mock_val + arg = args[0].query_input + mock_val = gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)) + assert arg == mock_val + + +def test_detect_intent_flattened_error(): + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.detect_intent( + gcd_session.DetectIntentRequest(), + session='session_value', + query_input=gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)), + ) + + +@pytest.mark.asyncio +async def test_detect_intent_flattened_async(): + client = SessionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.detect_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_session.DetectIntentResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_session.DetectIntentResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.detect_intent( + session='session_value', + query_input=gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].session + mock_val = 'session_value' + assert arg == mock_val + arg = args[0].query_input + mock_val = gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_detect_intent_flattened_error_async(): + client = SessionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.detect_intent( + gcd_session.DetectIntentRequest(), + session='session_value', + query_input=gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)), + ) + + +def test_streaming_detect_intent(transport: str = 'grpc', request_type=session.StreamingDetectIntentRequest): + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.streaming_detect_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iter([session.StreamingDetectIntentResponse()]) + response = client.streaming_detect_intent(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, session.StreamingDetectIntentResponse) + + +def test_streaming_detect_intent_from_dict(): + test_streaming_detect_intent(request_type=dict) + + +@pytest.mark.asyncio +async def test_streaming_detect_intent_async(transport: str = 'grpc_asyncio', request_type=session.StreamingDetectIntentRequest): + client = SessionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.streaming_detect_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock(side_effect=[session.StreamingDetectIntentResponse()]) + response = await client.streaming_detect_intent(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, session.StreamingDetectIntentResponse) + + +@pytest.mark.asyncio +async def test_streaming_detect_intent_async_from_dict(): + await test_streaming_detect_intent_async(request_type=dict) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SessionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SessionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SessionsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SessionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SessionsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SessionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SessionsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SessionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SessionsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SessionsGrpcTransport, + transports.SessionsGrpcAsyncIOTransport, +]) +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 = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SessionsGrpcTransport, + ) + +def test_sessions_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SessionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_sessions_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2.services.sessions.transports.SessionsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SessionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'detect_intent', + 'streaming_detect_intent', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_sessions_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.dialogflow_v2.services.sessions.transports.SessionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SessionsTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_sessions_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.dialogflow_v2.services.sessions.transports.SessionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SessionsTransport() + adc.assert_called_once() + + +def test_sessions_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) + SessionsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SessionsGrpcTransport, + transports.SessionsGrpcAsyncIOTransport, + ], +) +def test_sessions_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionsGrpcTransport, grpc_helpers), + (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_sessions_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport]) +def test_sessions_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_sessions_host_no_port(): + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_sessions_host_with_port(): + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_sessions_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SessionsGrpcTransport( + 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_sessions_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SessionsGrpcAsyncIOTransport( + 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.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport]) +def test_sessions_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.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport]) +def test_sessions_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_context_path(): + project = "squid" + session = "clam" + context = "whelk" + expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) + actual = SessionsClient.context_path(project, session, context) + assert expected == actual + + +def test_parse_context_path(): + expected = { + "project": "octopus", + "session": "oyster", + "context": "nudibranch", + } + path = SessionsClient.context_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_context_path(path) + assert expected == actual + +def test_intent_path(): + project = "cuttlefish" + intent = "mussel" + expected = "projects/{project}/agent/intents/{intent}".format(project=project, intent=intent, ) + actual = SessionsClient.intent_path(project, intent) + assert expected == actual + + +def test_parse_intent_path(): + expected = { + "project": "winkle", + "intent": "nautilus", + } + path = SessionsClient.intent_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_intent_path(path) + assert expected == actual + +def test_session_path(): + project = "scallop" + session = "abalone" + expected = "projects/{project}/agent/sessions/{session}".format(project=project, session=session, ) + actual = SessionsClient.session_path(project, session) + assert expected == actual + + +def test_parse_session_path(): + expected = { + "project": "squid", + "session": "clam", + } + path = SessionsClient.session_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_session_path(path) + assert expected == actual + +def test_session_entity_type_path(): + project = "whelk" + session = "octopus" + entity_type = "oyster" + expected = "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format(project=project, session=session, entity_type=entity_type, ) + actual = SessionsClient.session_entity_type_path(project, session, entity_type) + assert expected == actual + + +def test_parse_session_entity_type_path(): + expected = { + "project": "nudibranch", + "session": "cuttlefish", + "entity_type": "mussel", + } + path = SessionsClient.session_entity_type_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_session_entity_type_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SessionsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = SessionsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = SessionsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = SessionsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SessionsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = SessionsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = SessionsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = SessionsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.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 = SessionsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = SessionsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.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.SessionsTransport, '_prep_wrapped_messages') as prep: + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SessionsTransport, '_prep_wrapped_messages') as prep: + transport_class = SessionsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SessionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_versions.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_versions.py new file mode 100644 index 000000000..4dacd3447 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_versions.py @@ -0,0 +1,2334 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.versions import VersionsAsyncClient +from google.cloud.dialogflow_v2.services.versions import VersionsClient +from google.cloud.dialogflow_v2.services.versions import pagers +from google.cloud.dialogflow_v2.services.versions import transports +from google.cloud.dialogflow_v2.types import version +from google.cloud.dialogflow_v2.types import version as gcd_version +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert VersionsClient._get_default_mtls_endpoint(None) is None + assert VersionsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert VersionsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert VersionsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert VersionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert VersionsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + VersionsClient, + VersionsAsyncClient, +]) +def test_versions_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.VersionsGrpcTransport, "grpc"), + (transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_versions_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + VersionsClient, + VersionsAsyncClient, +]) +def test_versions_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 == 'dialogflow.googleapis.com:443' + + +def test_versions_client_get_transport_class(): + transport = VersionsClient.get_transport_class() + available_transports = [ + transports.VersionsGrpcTransport, + ] + assert transport in available_transports + + transport = VersionsClient.get_transport_class("grpc") + assert transport == transports.VersionsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient)) +@mock.patch.object(VersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsAsyncClient)) +def test_versions_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(VersionsClient, '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(VersionsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc", "true"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (VersionsClient, transports.VersionsGrpcTransport, "grpc", "false"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient)) +@mock.patch.object(VersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_versions_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_versions_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_versions_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_versions_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2.services.versions.transports.VersionsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = VersionsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_versions(transport: str = 'grpc', request_type=version.ListVersionsRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = version.ListVersionsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == version.ListVersionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListVersionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_versions_from_dict(): + test_list_versions(request_type=dict) + + +def test_list_versions_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=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_versions), + '__call__') as call: + client.list_versions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == version.ListVersionsRequest() + + +@pytest.mark.asyncio +async def test_list_versions_async(transport: str = 'grpc_asyncio', request_type=version.ListVersionsRequest): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(version.ListVersionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == version.ListVersionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListVersionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_versions_async_from_dict(): + await test_list_versions_async(request_type=dict) + + +def test_list_versions_field_headers(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.ListVersionsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + call.return_value = version.ListVersionsResponse() + client.list_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_versions_field_headers_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.ListVersionsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(version.ListVersionsResponse()) + await client.list_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_versions_flattened(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = version.ListVersionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_versions( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_versions_flattened_error(): + client = VersionsClient( + credentials=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_versions( + version.ListVersionsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_versions_flattened_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = version.ListVersionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(version.ListVersionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_versions( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_versions_flattened_error_async(): + client = VersionsAsyncClient( + credentials=ga_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_versions( + version.ListVersionsRequest(), + parent='parent_value', + ) + + +def test_list_versions_pager(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + version.Version(), + ], + next_page_token='abc', + ), + version.ListVersionsResponse( + versions=[], + next_page_token='def', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + ], + next_page_token='ghi', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_versions(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, version.Version) + for i in results) + +def test_list_versions_pages(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + version.Version(), + ], + next_page_token='abc', + ), + version.ListVersionsResponse( + versions=[], + next_page_token='def', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + ], + next_page_token='ghi', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + ], + ), + RuntimeError, + ) + pages = list(client.list_versions(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_versions_async_pager(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + version.Version(), + ], + next_page_token='abc', + ), + version.ListVersionsResponse( + versions=[], + next_page_token='def', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + ], + next_page_token='ghi', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_versions(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, version.Version) + for i in responses) + +@pytest.mark.asyncio +async def test_list_versions_async_pages(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + version.Version(), + ], + next_page_token='abc', + ), + version.ListVersionsResponse( + versions=[], + next_page_token='def', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + ], + next_page_token='ghi', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_versions(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_version(transport: str = 'grpc', request_type=version.GetVersionRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = version.Version( + name='name_value', + description='description_value', + version_number=1518, + status=version.Version.VersionStatus.IN_PROGRESS, + ) + response = client.get_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == version.GetVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, version.Version) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.version_number == 1518 + assert response.status == version.Version.VersionStatus.IN_PROGRESS + + +def test_get_version_from_dict(): + test_get_version(request_type=dict) + + +def test_get_version_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=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_version), + '__call__') as call: + client.get_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == version.GetVersionRequest() + + +@pytest.mark.asyncio +async def test_get_version_async(transport: str = 'grpc_asyncio', request_type=version.GetVersionRequest): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(version.Version( + name='name_value', + description='description_value', + version_number=1518, + status=version.Version.VersionStatus.IN_PROGRESS, + )) + response = await client.get_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == version.GetVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, version.Version) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.version_number == 1518 + assert response.status == version.Version.VersionStatus.IN_PROGRESS + + +@pytest.mark.asyncio +async def test_get_version_async_from_dict(): + await test_get_version_async(request_type=dict) + + +def test_get_version_field_headers(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.GetVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_version), + '__call__') as call: + call.return_value = version.Version() + client.get_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_version_field_headers_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.GetVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(version.Version()) + await client.get_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_version_flattened(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = version.Version() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_version( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_version_flattened_error(): + client = VersionsClient( + credentials=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_version( + version.GetVersionRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_version_flattened_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = version.Version() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(version.Version()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_version( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_version_flattened_error_async(): + client = VersionsAsyncClient( + credentials=ga_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_version( + version.GetVersionRequest(), + name='name_value', + ) + + +def test_create_version(transport: str = 'grpc', request_type=gcd_version.CreateVersionRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version( + name='name_value', + description='description_value', + version_number=1518, + status=gcd_version.Version.VersionStatus.IN_PROGRESS, + ) + response = client.create_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.CreateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_version.Version) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.version_number == 1518 + assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS + + +def test_create_version_from_dict(): + test_create_version(request_type=dict) + + +def test_create_version_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=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_version), + '__call__') as call: + client.create_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.CreateVersionRequest() + + +@pytest.mark.asyncio +async def test_create_version_async(transport: str = 'grpc_asyncio', request_type=gcd_version.CreateVersionRequest): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version( + name='name_value', + description='description_value', + version_number=1518, + status=gcd_version.Version.VersionStatus.IN_PROGRESS, + )) + response = await client.create_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.CreateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_version.Version) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.version_number == 1518 + assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS + + +@pytest.mark.asyncio +async def test_create_version_async_from_dict(): + await test_create_version_async(request_type=dict) + + +def test_create_version_field_headers(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_version.CreateVersionRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + call.return_value = gcd_version.Version() + client.create_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_version_field_headers_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_version.CreateVersionRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version()) + await client.create_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_version_flattened(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_version( + parent='parent_value', + version=gcd_version.Version(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].version + mock_val = gcd_version.Version(name='name_value') + assert arg == mock_val + + +def test_create_version_flattened_error(): + client = VersionsClient( + credentials=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_version( + gcd_version.CreateVersionRequest(), + parent='parent_value', + version=gcd_version.Version(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_version_flattened_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_version( + parent='parent_value', + version=gcd_version.Version(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].version + mock_val = gcd_version.Version(name='name_value') + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_version_flattened_error_async(): + client = VersionsAsyncClient( + credentials=ga_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_version( + gcd_version.CreateVersionRequest(), + parent='parent_value', + version=gcd_version.Version(name='name_value'), + ) + + +def test_update_version(transport: str = 'grpc', request_type=gcd_version.UpdateVersionRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version( + name='name_value', + description='description_value', + version_number=1518, + status=gcd_version.Version.VersionStatus.IN_PROGRESS, + ) + response = client.update_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.UpdateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_version.Version) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.version_number == 1518 + assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS + + +def test_update_version_from_dict(): + test_update_version(request_type=dict) + + +def test_update_version_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=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_version), + '__call__') as call: + client.update_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.UpdateVersionRequest() + + +@pytest.mark.asyncio +async def test_update_version_async(transport: str = 'grpc_asyncio', request_type=gcd_version.UpdateVersionRequest): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version( + name='name_value', + description='description_value', + version_number=1518, + status=gcd_version.Version.VersionStatus.IN_PROGRESS, + )) + response = await client.update_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.UpdateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_version.Version) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.version_number == 1518 + assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS + + +@pytest.mark.asyncio +async def test_update_version_async_from_dict(): + await test_update_version_async(request_type=dict) + + +def test_update_version_field_headers(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_version.UpdateVersionRequest() + + request.version.name = 'version.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + call.return_value = gcd_version.Version() + client.update_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'version.name=version.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_version_field_headers_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_version.UpdateVersionRequest() + + request.version.name = 'version.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version()) + await client.update_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'version.name=version.name/value', + ) in kw['metadata'] + + +def test_update_version_flattened(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_version( + version=gcd_version.Version(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].version + mock_val = gcd_version.Version(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_version_flattened_error(): + client = VersionsClient( + credentials=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_version( + gcd_version.UpdateVersionRequest(), + version=gcd_version.Version(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_version_flattened_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_version( + version=gcd_version.Version(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].version + mock_val = gcd_version.Version(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_version_flattened_error_async(): + client = VersionsAsyncClient( + credentials=ga_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_version( + gcd_version.UpdateVersionRequest(), + version=gcd_version.Version(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_version(transport: str = 'grpc', request_type=version.DeleteVersionRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == version.DeleteVersionRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_version_from_dict(): + test_delete_version(request_type=dict) + + +def test_delete_version_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=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_version), + '__call__') as call: + client.delete_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == version.DeleteVersionRequest() + + +@pytest.mark.asyncio +async def test_delete_version_async(transport: str = 'grpc_asyncio', request_type=version.DeleteVersionRequest): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == version.DeleteVersionRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_version_async_from_dict(): + await test_delete_version_async(request_type=dict) + + +def test_delete_version_field_headers(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.DeleteVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_version), + '__call__') as call: + call.return_value = None + client.delete_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_version_field_headers_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.DeleteVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_version_flattened(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_version), + '__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_version( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_version_flattened_error(): + client = VersionsClient( + credentials=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_version( + version.DeleteVersionRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_version_flattened_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_version), + '__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_version( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_version_flattened_error_async(): + client = VersionsAsyncClient( + credentials=ga_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_version( + version.DeleteVersionRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VersionsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VersionsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = VersionsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.VersionsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.VersionsGrpcTransport, + transports.VersionsGrpcAsyncIOTransport, +]) +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 = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.VersionsGrpcTransport, + ) + +def test_versions_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.VersionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_versions_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2.services.versions.transports.VersionsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.VersionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_versions', + 'get_version', + 'create_version', + 'update_version', + 'delete_version', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_versions_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.dialogflow_v2.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VersionsTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_versions_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.dialogflow_v2.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VersionsTransport() + adc.assert_called_once() + + +def test_versions_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) + VersionsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.VersionsGrpcTransport, + transports.VersionsGrpcAsyncIOTransport, + ], +) +def test_versions_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.VersionsGrpcTransport, grpc_helpers), + (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_versions_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport]) +def test_versions_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_versions_host_no_port(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_versions_host_with_port(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_versions_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VersionsGrpcTransport( + 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_versions_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VersionsGrpcAsyncIOTransport( + 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.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport]) +def test_versions_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.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport]) +def test_versions_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_version_path(): + project = "squid" + version = "clam" + expected = "projects/{project}/agent/versions/{version}".format(project=project, version=version, ) + actual = VersionsClient.version_path(project, version) + assert expected == actual + + +def test_parse_version_path(): + expected = { + "project": "whelk", + "version": "octopus", + } + path = VersionsClient.version_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_version_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = VersionsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = VersionsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = VersionsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = VersionsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = VersionsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = VersionsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = VersionsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = VersionsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = VersionsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = VersionsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.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.VersionsTransport, '_prep_wrapped_messages') as prep: + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.VersionsTransport, '_prep_wrapped_messages') as prep: + transport_class = VersionsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2beta1/.coveragerc b/owl-bot-staging/v2beta1/.coveragerc new file mode 100644 index 000000000..09666453e --- /dev/null +++ b/owl-bot-staging/v2beta1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/dialogflow/__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/v2beta1/MANIFEST.in b/owl-bot-staging/v2beta1/MANIFEST.in new file mode 100644 index 000000000..a267e6fb4 --- /dev/null +++ b/owl-bot-staging/v2beta1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/dialogflow *.py +recursive-include google/cloud/dialogflow_v2beta1 *.py diff --git a/owl-bot-staging/v2beta1/README.rst b/owl-bot-staging/v2beta1/README.rst new file mode 100644 index 000000000..6a2fa7289 --- /dev/null +++ b/owl-bot-staging/v2beta1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Dialogflow 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 Dialogflow 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/v2beta1/docs/conf.py b/owl-bot-staging/v2beta1/docs/conf.py new file mode 100644 index 000000000..8b2599a7e --- /dev/null +++ b/owl-bot-staging/v2beta1/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-dialogflow 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-dialogflow" +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-dialogflow-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-dialogflow.tex", + u"google-cloud-dialogflow 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-dialogflow", + u"Google Cloud Dialogflow 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-dialogflow", + u"google-cloud-dialogflow Documentation", + author, + "google-cloud-dialogflow", + "GAPIC library for Google Cloud Dialogflow 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/v2beta1/docs/dialogflow_v2beta1/agents.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/agents.rst new file mode 100644 index 000000000..154fdf432 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/agents.rst @@ -0,0 +1,10 @@ +Agents +------------------------ + +.. automodule:: google.cloud.dialogflow_v2beta1.services.agents + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2beta1.services.agents.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/answer_records.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/answer_records.rst new file mode 100644 index 000000000..1f890c79c --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/answer_records.rst @@ -0,0 +1,10 @@ +AnswerRecords +------------------------------- + +.. automodule:: google.cloud.dialogflow_v2beta1.services.answer_records + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2beta1.services.answer_records.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/contexts.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/contexts.rst new file mode 100644 index 000000000..e6be19355 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/contexts.rst @@ -0,0 +1,10 @@ +Contexts +-------------------------- + +.. automodule:: google.cloud.dialogflow_v2beta1.services.contexts + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2beta1.services.contexts.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/conversation_profiles.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/conversation_profiles.rst new file mode 100644 index 000000000..959fe3698 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/conversation_profiles.rst @@ -0,0 +1,10 @@ +ConversationProfiles +-------------------------------------- + +.. automodule:: google.cloud.dialogflow_v2beta1.services.conversation_profiles + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2beta1.services.conversation_profiles.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/conversations.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/conversations.rst new file mode 100644 index 000000000..60267bd79 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/conversations.rst @@ -0,0 +1,10 @@ +Conversations +------------------------------- + +.. automodule:: google.cloud.dialogflow_v2beta1.services.conversations + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2beta1.services.conversations.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/documents.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/documents.rst new file mode 100644 index 000000000..7151feda6 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/documents.rst @@ -0,0 +1,10 @@ +Documents +--------------------------- + +.. automodule:: google.cloud.dialogflow_v2beta1.services.documents + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2beta1.services.documents.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/entity_types.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/entity_types.rst new file mode 100644 index 000000000..99defb836 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/entity_types.rst @@ -0,0 +1,10 @@ +EntityTypes +----------------------------- + +.. automodule:: google.cloud.dialogflow_v2beta1.services.entity_types + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2beta1.services.entity_types.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/environments.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/environments.rst new file mode 100644 index 000000000..3c4d6f333 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/environments.rst @@ -0,0 +1,10 @@ +Environments +------------------------------ + +.. automodule:: google.cloud.dialogflow_v2beta1.services.environments + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2beta1.services.environments.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/fulfillments.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/fulfillments.rst new file mode 100644 index 000000000..33be7d8a0 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/fulfillments.rst @@ -0,0 +1,6 @@ +Fulfillments +------------------------------ + +.. automodule:: google.cloud.dialogflow_v2beta1.services.fulfillments + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/intents.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/intents.rst new file mode 100644 index 000000000..50e85e80d --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/intents.rst @@ -0,0 +1,10 @@ +Intents +------------------------- + +.. automodule:: google.cloud.dialogflow_v2beta1.services.intents + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2beta1.services.intents.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/knowledge_bases.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/knowledge_bases.rst new file mode 100644 index 000000000..70e0d5ab6 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/knowledge_bases.rst @@ -0,0 +1,10 @@ +KnowledgeBases +-------------------------------- + +.. automodule:: google.cloud.dialogflow_v2beta1.services.knowledge_bases + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2beta1.services.knowledge_bases.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/participants.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/participants.rst new file mode 100644 index 000000000..b2a73ebe3 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/participants.rst @@ -0,0 +1,10 @@ +Participants +------------------------------ + +.. automodule:: google.cloud.dialogflow_v2beta1.services.participants + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2beta1.services.participants.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/services.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/services.rst new file mode 100644 index 000000000..dc7790aa3 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/services.rst @@ -0,0 +1,20 @@ +Services for Google Cloud Dialogflow v2beta1 API +================================================ +.. toctree:: + :maxdepth: 2 + + agents + answer_records + contexts + conversation_profiles + conversations + documents + entity_types + environments + fulfillments + intents + knowledge_bases + participants + session_entity_types + sessions + versions diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/session_entity_types.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/session_entity_types.rst new file mode 100644 index 000000000..4fe3bcb31 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/session_entity_types.rst @@ -0,0 +1,10 @@ +SessionEntityTypes +------------------------------------ + +.. automodule:: google.cloud.dialogflow_v2beta1.services.session_entity_types + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2beta1.services.session_entity_types.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/sessions.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/sessions.rst new file mode 100644 index 000000000..da6517c63 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/sessions.rst @@ -0,0 +1,6 @@ +Sessions +-------------------------- + +.. automodule:: google.cloud.dialogflow_v2beta1.services.sessions + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/types.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/types.rst new file mode 100644 index 000000000..f4c430d5a --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Dialogflow v2beta1 API +============================================= + +.. automodule:: google.cloud.dialogflow_v2beta1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/versions.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/versions.rst new file mode 100644 index 000000000..c74ba0edf --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/versions.rst @@ -0,0 +1,10 @@ +Versions +-------------------------- + +.. automodule:: google.cloud.dialogflow_v2beta1.services.versions + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2beta1.services.versions.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/index.rst b/owl-bot-staging/v2beta1/docs/index.rst new file mode 100644 index 000000000..ffce78914 --- /dev/null +++ b/owl-bot-staging/v2beta1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + dialogflow_v2beta1/services + dialogflow_v2beta1/types diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow/__init__.py new file mode 100644 index 000000000..ae9445c97 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow/__init__.py @@ -0,0 +1,465 @@ +# -*- 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.dialogflow_v2beta1.services.agents.client import AgentsClient +from google.cloud.dialogflow_v2beta1.services.agents.async_client import AgentsAsyncClient +from google.cloud.dialogflow_v2beta1.services.answer_records.client import AnswerRecordsClient +from google.cloud.dialogflow_v2beta1.services.answer_records.async_client import AnswerRecordsAsyncClient +from google.cloud.dialogflow_v2beta1.services.contexts.client import ContextsClient +from google.cloud.dialogflow_v2beta1.services.contexts.async_client import ContextsAsyncClient +from google.cloud.dialogflow_v2beta1.services.conversation_profiles.client import ConversationProfilesClient +from google.cloud.dialogflow_v2beta1.services.conversation_profiles.async_client import ConversationProfilesAsyncClient +from google.cloud.dialogflow_v2beta1.services.conversations.client import ConversationsClient +from google.cloud.dialogflow_v2beta1.services.conversations.async_client import ConversationsAsyncClient +from google.cloud.dialogflow_v2beta1.services.documents.client import DocumentsClient +from google.cloud.dialogflow_v2beta1.services.documents.async_client import DocumentsAsyncClient +from google.cloud.dialogflow_v2beta1.services.entity_types.client import EntityTypesClient +from google.cloud.dialogflow_v2beta1.services.entity_types.async_client import EntityTypesAsyncClient +from google.cloud.dialogflow_v2beta1.services.environments.client import EnvironmentsClient +from google.cloud.dialogflow_v2beta1.services.environments.async_client import EnvironmentsAsyncClient +from google.cloud.dialogflow_v2beta1.services.fulfillments.client import FulfillmentsClient +from google.cloud.dialogflow_v2beta1.services.fulfillments.async_client import FulfillmentsAsyncClient +from google.cloud.dialogflow_v2beta1.services.intents.client import IntentsClient +from google.cloud.dialogflow_v2beta1.services.intents.async_client import IntentsAsyncClient +from google.cloud.dialogflow_v2beta1.services.knowledge_bases.client import KnowledgeBasesClient +from google.cloud.dialogflow_v2beta1.services.knowledge_bases.async_client import KnowledgeBasesAsyncClient +from google.cloud.dialogflow_v2beta1.services.participants.client import ParticipantsClient +from google.cloud.dialogflow_v2beta1.services.participants.async_client import ParticipantsAsyncClient +from google.cloud.dialogflow_v2beta1.services.session_entity_types.client import SessionEntityTypesClient +from google.cloud.dialogflow_v2beta1.services.session_entity_types.async_client import SessionEntityTypesAsyncClient +from google.cloud.dialogflow_v2beta1.services.sessions.client import SessionsClient +from google.cloud.dialogflow_v2beta1.services.sessions.async_client import SessionsAsyncClient +from google.cloud.dialogflow_v2beta1.services.versions.client import VersionsClient +from google.cloud.dialogflow_v2beta1.services.versions.async_client import VersionsAsyncClient + +from google.cloud.dialogflow_v2beta1.types.agent import Agent +from google.cloud.dialogflow_v2beta1.types.agent import DeleteAgentRequest +from google.cloud.dialogflow_v2beta1.types.agent import ExportAgentRequest +from google.cloud.dialogflow_v2beta1.types.agent import ExportAgentResponse +from google.cloud.dialogflow_v2beta1.types.agent import GetAgentRequest +from google.cloud.dialogflow_v2beta1.types.agent import GetValidationResultRequest +from google.cloud.dialogflow_v2beta1.types.agent import ImportAgentRequest +from google.cloud.dialogflow_v2beta1.types.agent import RestoreAgentRequest +from google.cloud.dialogflow_v2beta1.types.agent import SearchAgentsRequest +from google.cloud.dialogflow_v2beta1.types.agent import SearchAgentsResponse +from google.cloud.dialogflow_v2beta1.types.agent import SetAgentRequest +from google.cloud.dialogflow_v2beta1.types.agent import SubAgent +from google.cloud.dialogflow_v2beta1.types.agent import TrainAgentRequest +from google.cloud.dialogflow_v2beta1.types.answer_record import AgentAssistantFeedback +from google.cloud.dialogflow_v2beta1.types.answer_record import AgentAssistantRecord +from google.cloud.dialogflow_v2beta1.types.answer_record import AnswerFeedback +from google.cloud.dialogflow_v2beta1.types.answer_record import AnswerRecord +from google.cloud.dialogflow_v2beta1.types.answer_record import GetAnswerRecordRequest +from google.cloud.dialogflow_v2beta1.types.answer_record import ListAnswerRecordsRequest +from google.cloud.dialogflow_v2beta1.types.answer_record import ListAnswerRecordsResponse +from google.cloud.dialogflow_v2beta1.types.answer_record import UpdateAnswerRecordRequest +from google.cloud.dialogflow_v2beta1.types.audio_config import InputAudioConfig +from google.cloud.dialogflow_v2beta1.types.audio_config import OutputAudioConfig +from google.cloud.dialogflow_v2beta1.types.audio_config import SpeechContext +from google.cloud.dialogflow_v2beta1.types.audio_config import SpeechToTextConfig +from google.cloud.dialogflow_v2beta1.types.audio_config import SpeechWordInfo +from google.cloud.dialogflow_v2beta1.types.audio_config import SynthesizeSpeechConfig +from google.cloud.dialogflow_v2beta1.types.audio_config import TelephonyDtmfEvents +from google.cloud.dialogflow_v2beta1.types.audio_config import VoiceSelectionParams +from google.cloud.dialogflow_v2beta1.types.audio_config import AudioEncoding +from google.cloud.dialogflow_v2beta1.types.audio_config import OutputAudioEncoding +from google.cloud.dialogflow_v2beta1.types.audio_config import SpeechModelVariant +from google.cloud.dialogflow_v2beta1.types.audio_config import SsmlVoiceGender +from google.cloud.dialogflow_v2beta1.types.audio_config import TelephonyDtmf +from google.cloud.dialogflow_v2beta1.types.context import Context +from google.cloud.dialogflow_v2beta1.types.context import CreateContextRequest +from google.cloud.dialogflow_v2beta1.types.context import DeleteAllContextsRequest +from google.cloud.dialogflow_v2beta1.types.context import DeleteContextRequest +from google.cloud.dialogflow_v2beta1.types.context import GetContextRequest +from google.cloud.dialogflow_v2beta1.types.context import ListContextsRequest +from google.cloud.dialogflow_v2beta1.types.context import ListContextsResponse +from google.cloud.dialogflow_v2beta1.types.context import UpdateContextRequest +from google.cloud.dialogflow_v2beta1.types.conversation import BatchCreateMessagesRequest +from google.cloud.dialogflow_v2beta1.types.conversation import BatchCreateMessagesResponse +from google.cloud.dialogflow_v2beta1.types.conversation import CompleteConversationRequest +from google.cloud.dialogflow_v2beta1.types.conversation import Conversation +from google.cloud.dialogflow_v2beta1.types.conversation import ConversationPhoneNumber +from google.cloud.dialogflow_v2beta1.types.conversation import CreateConversationRequest +from google.cloud.dialogflow_v2beta1.types.conversation import CreateMessageRequest +from google.cloud.dialogflow_v2beta1.types.conversation import GetConversationRequest +from google.cloud.dialogflow_v2beta1.types.conversation import ListConversationsRequest +from google.cloud.dialogflow_v2beta1.types.conversation import ListConversationsResponse +from google.cloud.dialogflow_v2beta1.types.conversation import ListMessagesRequest +from google.cloud.dialogflow_v2beta1.types.conversation import ListMessagesResponse +from google.cloud.dialogflow_v2beta1.types.conversation_event import ConversationEvent +from google.cloud.dialogflow_v2beta1.types.conversation_profile import AutomatedAgentConfig +from google.cloud.dialogflow_v2beta1.types.conversation_profile import ConversationProfile +from google.cloud.dialogflow_v2beta1.types.conversation_profile import CreateConversationProfileRequest +from google.cloud.dialogflow_v2beta1.types.conversation_profile import DeleteConversationProfileRequest +from google.cloud.dialogflow_v2beta1.types.conversation_profile import GetConversationProfileRequest +from google.cloud.dialogflow_v2beta1.types.conversation_profile import HumanAgentAssistantConfig +from google.cloud.dialogflow_v2beta1.types.conversation_profile import HumanAgentHandoffConfig +from google.cloud.dialogflow_v2beta1.types.conversation_profile import ListConversationProfilesRequest +from google.cloud.dialogflow_v2beta1.types.conversation_profile import ListConversationProfilesResponse +from google.cloud.dialogflow_v2beta1.types.conversation_profile import LoggingConfig +from google.cloud.dialogflow_v2beta1.types.conversation_profile import NotificationConfig +from google.cloud.dialogflow_v2beta1.types.conversation_profile import UpdateConversationProfileRequest +from google.cloud.dialogflow_v2beta1.types.document import CreateDocumentRequest +from google.cloud.dialogflow_v2beta1.types.document import DeleteDocumentRequest +from google.cloud.dialogflow_v2beta1.types.document import Document +from google.cloud.dialogflow_v2beta1.types.document import GetDocumentRequest +from google.cloud.dialogflow_v2beta1.types.document import ImportDocumentsRequest +from google.cloud.dialogflow_v2beta1.types.document import ImportDocumentsResponse +from google.cloud.dialogflow_v2beta1.types.document import ImportDocumentTemplate +from google.cloud.dialogflow_v2beta1.types.document import KnowledgeOperationMetadata +from google.cloud.dialogflow_v2beta1.types.document import ListDocumentsRequest +from google.cloud.dialogflow_v2beta1.types.document import ListDocumentsResponse +from google.cloud.dialogflow_v2beta1.types.document import ReloadDocumentRequest +from google.cloud.dialogflow_v2beta1.types.document import UpdateDocumentRequest +from google.cloud.dialogflow_v2beta1.types.entity_type import BatchCreateEntitiesRequest +from google.cloud.dialogflow_v2beta1.types.entity_type import BatchDeleteEntitiesRequest +from google.cloud.dialogflow_v2beta1.types.entity_type import BatchDeleteEntityTypesRequest +from google.cloud.dialogflow_v2beta1.types.entity_type import BatchUpdateEntitiesRequest +from google.cloud.dialogflow_v2beta1.types.entity_type import BatchUpdateEntityTypesRequest +from google.cloud.dialogflow_v2beta1.types.entity_type import BatchUpdateEntityTypesResponse +from google.cloud.dialogflow_v2beta1.types.entity_type import CreateEntityTypeRequest +from google.cloud.dialogflow_v2beta1.types.entity_type import DeleteEntityTypeRequest +from google.cloud.dialogflow_v2beta1.types.entity_type import EntityType +from google.cloud.dialogflow_v2beta1.types.entity_type import EntityTypeBatch +from google.cloud.dialogflow_v2beta1.types.entity_type import GetEntityTypeRequest +from google.cloud.dialogflow_v2beta1.types.entity_type import ListEntityTypesRequest +from google.cloud.dialogflow_v2beta1.types.entity_type import ListEntityTypesResponse +from google.cloud.dialogflow_v2beta1.types.entity_type import UpdateEntityTypeRequest +from google.cloud.dialogflow_v2beta1.types.environment import CreateEnvironmentRequest +from google.cloud.dialogflow_v2beta1.types.environment import DeleteEnvironmentRequest +from google.cloud.dialogflow_v2beta1.types.environment import Environment +from google.cloud.dialogflow_v2beta1.types.environment import EnvironmentHistory +from google.cloud.dialogflow_v2beta1.types.environment import GetEnvironmentHistoryRequest +from google.cloud.dialogflow_v2beta1.types.environment import GetEnvironmentRequest +from google.cloud.dialogflow_v2beta1.types.environment import ListEnvironmentsRequest +from google.cloud.dialogflow_v2beta1.types.environment import ListEnvironmentsResponse +from google.cloud.dialogflow_v2beta1.types.environment import TextToSpeechSettings +from google.cloud.dialogflow_v2beta1.types.environment import UpdateEnvironmentRequest +from google.cloud.dialogflow_v2beta1.types.fulfillment import Fulfillment +from google.cloud.dialogflow_v2beta1.types.fulfillment import GetFulfillmentRequest +from google.cloud.dialogflow_v2beta1.types.fulfillment import UpdateFulfillmentRequest +from google.cloud.dialogflow_v2beta1.types.gcs import GcsSource +from google.cloud.dialogflow_v2beta1.types.gcs import GcsSources +from google.cloud.dialogflow_v2beta1.types.human_agent_assistant_event import HumanAgentAssistantEvent +from google.cloud.dialogflow_v2beta1.types.intent import BatchDeleteIntentsRequest +from google.cloud.dialogflow_v2beta1.types.intent import BatchUpdateIntentsRequest +from google.cloud.dialogflow_v2beta1.types.intent import BatchUpdateIntentsResponse +from google.cloud.dialogflow_v2beta1.types.intent import CreateIntentRequest +from google.cloud.dialogflow_v2beta1.types.intent import DeleteIntentRequest +from google.cloud.dialogflow_v2beta1.types.intent import GetIntentRequest +from google.cloud.dialogflow_v2beta1.types.intent import Intent +from google.cloud.dialogflow_v2beta1.types.intent import IntentBatch +from google.cloud.dialogflow_v2beta1.types.intent import ListIntentsRequest +from google.cloud.dialogflow_v2beta1.types.intent import ListIntentsResponse +from google.cloud.dialogflow_v2beta1.types.intent import UpdateIntentRequest +from google.cloud.dialogflow_v2beta1.types.intent import IntentView +from google.cloud.dialogflow_v2beta1.types.knowledge_base import CreateKnowledgeBaseRequest +from google.cloud.dialogflow_v2beta1.types.knowledge_base import DeleteKnowledgeBaseRequest +from google.cloud.dialogflow_v2beta1.types.knowledge_base import GetKnowledgeBaseRequest +from google.cloud.dialogflow_v2beta1.types.knowledge_base import KnowledgeBase +from google.cloud.dialogflow_v2beta1.types.knowledge_base import ListKnowledgeBasesRequest +from google.cloud.dialogflow_v2beta1.types.knowledge_base import ListKnowledgeBasesResponse +from google.cloud.dialogflow_v2beta1.types.knowledge_base import UpdateKnowledgeBaseRequest +from google.cloud.dialogflow_v2beta1.types.participant import AnalyzeContentRequest +from google.cloud.dialogflow_v2beta1.types.participant import AnalyzeContentResponse +from google.cloud.dialogflow_v2beta1.types.participant import AnnotatedMessagePart +from google.cloud.dialogflow_v2beta1.types.participant import ArticleAnswer +from google.cloud.dialogflow_v2beta1.types.participant import AssistQueryParameters +from google.cloud.dialogflow_v2beta1.types.participant import AutomatedAgentReply +from google.cloud.dialogflow_v2beta1.types.participant import CompileSuggestionRequest +from google.cloud.dialogflow_v2beta1.types.participant import CompileSuggestionResponse +from google.cloud.dialogflow_v2beta1.types.participant import CreateParticipantRequest +from google.cloud.dialogflow_v2beta1.types.participant import DtmfParameters +from google.cloud.dialogflow_v2beta1.types.participant import FaqAnswer +from google.cloud.dialogflow_v2beta1.types.participant import GetParticipantRequest +from google.cloud.dialogflow_v2beta1.types.participant import ListParticipantsRequest +from google.cloud.dialogflow_v2beta1.types.participant import ListParticipantsResponse +from google.cloud.dialogflow_v2beta1.types.participant import ListSuggestionsRequest +from google.cloud.dialogflow_v2beta1.types.participant import ListSuggestionsResponse +from google.cloud.dialogflow_v2beta1.types.participant import Message +from google.cloud.dialogflow_v2beta1.types.participant import MessageAnnotation +from google.cloud.dialogflow_v2beta1.types.participant import OutputAudio +from google.cloud.dialogflow_v2beta1.types.participant import Participant +from google.cloud.dialogflow_v2beta1.types.participant import ResponseMessage +from google.cloud.dialogflow_v2beta1.types.participant import SmartReplyAnswer +from google.cloud.dialogflow_v2beta1.types.participant import SuggestArticlesRequest +from google.cloud.dialogflow_v2beta1.types.participant import SuggestArticlesResponse +from google.cloud.dialogflow_v2beta1.types.participant import SuggestFaqAnswersRequest +from google.cloud.dialogflow_v2beta1.types.participant import SuggestFaqAnswersResponse +from google.cloud.dialogflow_v2beta1.types.participant import Suggestion +from google.cloud.dialogflow_v2beta1.types.participant import SuggestionFeature +from google.cloud.dialogflow_v2beta1.types.participant import SuggestionResult +from google.cloud.dialogflow_v2beta1.types.participant import SuggestSmartRepliesRequest +from google.cloud.dialogflow_v2beta1.types.participant import SuggestSmartRepliesResponse +from google.cloud.dialogflow_v2beta1.types.participant import UpdateParticipantRequest +from google.cloud.dialogflow_v2beta1.types.session import DetectIntentRequest +from google.cloud.dialogflow_v2beta1.types.session import DetectIntentResponse +from google.cloud.dialogflow_v2beta1.types.session import EventInput +from google.cloud.dialogflow_v2beta1.types.session import KnowledgeAnswers +from google.cloud.dialogflow_v2beta1.types.session import QueryInput +from google.cloud.dialogflow_v2beta1.types.session import QueryParameters +from google.cloud.dialogflow_v2beta1.types.session import QueryResult +from google.cloud.dialogflow_v2beta1.types.session import Sentiment +from google.cloud.dialogflow_v2beta1.types.session import SentimentAnalysisRequestConfig +from google.cloud.dialogflow_v2beta1.types.session import SentimentAnalysisResult +from google.cloud.dialogflow_v2beta1.types.session import StreamingDetectIntentRequest +from google.cloud.dialogflow_v2beta1.types.session import StreamingDetectIntentResponse +from google.cloud.dialogflow_v2beta1.types.session import StreamingRecognitionResult +from google.cloud.dialogflow_v2beta1.types.session import TextInput +from google.cloud.dialogflow_v2beta1.types.session_entity_type import CreateSessionEntityTypeRequest +from google.cloud.dialogflow_v2beta1.types.session_entity_type import DeleteSessionEntityTypeRequest +from google.cloud.dialogflow_v2beta1.types.session_entity_type import GetSessionEntityTypeRequest +from google.cloud.dialogflow_v2beta1.types.session_entity_type import ListSessionEntityTypesRequest +from google.cloud.dialogflow_v2beta1.types.session_entity_type import ListSessionEntityTypesResponse +from google.cloud.dialogflow_v2beta1.types.session_entity_type import SessionEntityType +from google.cloud.dialogflow_v2beta1.types.session_entity_type import UpdateSessionEntityTypeRequest +from google.cloud.dialogflow_v2beta1.types.validation_result import ValidationError +from google.cloud.dialogflow_v2beta1.types.validation_result import ValidationResult +from google.cloud.dialogflow_v2beta1.types.version import CreateVersionRequest +from google.cloud.dialogflow_v2beta1.types.version import DeleteVersionRequest +from google.cloud.dialogflow_v2beta1.types.version import GetVersionRequest +from google.cloud.dialogflow_v2beta1.types.version import ListVersionsRequest +from google.cloud.dialogflow_v2beta1.types.version import ListVersionsResponse +from google.cloud.dialogflow_v2beta1.types.version import UpdateVersionRequest +from google.cloud.dialogflow_v2beta1.types.version import Version +from google.cloud.dialogflow_v2beta1.types.webhook import OriginalDetectIntentRequest +from google.cloud.dialogflow_v2beta1.types.webhook import WebhookRequest +from google.cloud.dialogflow_v2beta1.types.webhook import WebhookResponse + +__all__ = ('AgentsClient', + 'AgentsAsyncClient', + 'AnswerRecordsClient', + 'AnswerRecordsAsyncClient', + 'ContextsClient', + 'ContextsAsyncClient', + 'ConversationProfilesClient', + 'ConversationProfilesAsyncClient', + 'ConversationsClient', + 'ConversationsAsyncClient', + 'DocumentsClient', + 'DocumentsAsyncClient', + 'EntityTypesClient', + 'EntityTypesAsyncClient', + 'EnvironmentsClient', + 'EnvironmentsAsyncClient', + 'FulfillmentsClient', + 'FulfillmentsAsyncClient', + 'IntentsClient', + 'IntentsAsyncClient', + 'KnowledgeBasesClient', + 'KnowledgeBasesAsyncClient', + 'ParticipantsClient', + 'ParticipantsAsyncClient', + 'SessionEntityTypesClient', + 'SessionEntityTypesAsyncClient', + 'SessionsClient', + 'SessionsAsyncClient', + 'VersionsClient', + 'VersionsAsyncClient', + 'Agent', + 'DeleteAgentRequest', + 'ExportAgentRequest', + 'ExportAgentResponse', + 'GetAgentRequest', + 'GetValidationResultRequest', + 'ImportAgentRequest', + 'RestoreAgentRequest', + 'SearchAgentsRequest', + 'SearchAgentsResponse', + 'SetAgentRequest', + 'SubAgent', + 'TrainAgentRequest', + 'AgentAssistantFeedback', + 'AgentAssistantRecord', + 'AnswerFeedback', + 'AnswerRecord', + 'GetAnswerRecordRequest', + 'ListAnswerRecordsRequest', + 'ListAnswerRecordsResponse', + 'UpdateAnswerRecordRequest', + 'InputAudioConfig', + 'OutputAudioConfig', + 'SpeechContext', + 'SpeechToTextConfig', + 'SpeechWordInfo', + 'SynthesizeSpeechConfig', + 'TelephonyDtmfEvents', + 'VoiceSelectionParams', + 'AudioEncoding', + 'OutputAudioEncoding', + 'SpeechModelVariant', + 'SsmlVoiceGender', + 'TelephonyDtmf', + 'Context', + 'CreateContextRequest', + 'DeleteAllContextsRequest', + 'DeleteContextRequest', + 'GetContextRequest', + 'ListContextsRequest', + 'ListContextsResponse', + 'UpdateContextRequest', + 'BatchCreateMessagesRequest', + 'BatchCreateMessagesResponse', + 'CompleteConversationRequest', + 'Conversation', + 'ConversationPhoneNumber', + 'CreateConversationRequest', + 'CreateMessageRequest', + 'GetConversationRequest', + 'ListConversationsRequest', + 'ListConversationsResponse', + 'ListMessagesRequest', + 'ListMessagesResponse', + 'ConversationEvent', + 'AutomatedAgentConfig', + 'ConversationProfile', + 'CreateConversationProfileRequest', + 'DeleteConversationProfileRequest', + 'GetConversationProfileRequest', + 'HumanAgentAssistantConfig', + 'HumanAgentHandoffConfig', + 'ListConversationProfilesRequest', + 'ListConversationProfilesResponse', + 'LoggingConfig', + 'NotificationConfig', + 'UpdateConversationProfileRequest', + 'CreateDocumentRequest', + 'DeleteDocumentRequest', + 'Document', + 'GetDocumentRequest', + 'ImportDocumentsRequest', + 'ImportDocumentsResponse', + 'ImportDocumentTemplate', + 'KnowledgeOperationMetadata', + 'ListDocumentsRequest', + 'ListDocumentsResponse', + 'ReloadDocumentRequest', + 'UpdateDocumentRequest', + 'BatchCreateEntitiesRequest', + 'BatchDeleteEntitiesRequest', + 'BatchDeleteEntityTypesRequest', + 'BatchUpdateEntitiesRequest', + 'BatchUpdateEntityTypesRequest', + 'BatchUpdateEntityTypesResponse', + 'CreateEntityTypeRequest', + 'DeleteEntityTypeRequest', + 'EntityType', + 'EntityTypeBatch', + 'GetEntityTypeRequest', + 'ListEntityTypesRequest', + 'ListEntityTypesResponse', + 'UpdateEntityTypeRequest', + 'CreateEnvironmentRequest', + 'DeleteEnvironmentRequest', + 'Environment', + 'EnvironmentHistory', + 'GetEnvironmentHistoryRequest', + 'GetEnvironmentRequest', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'TextToSpeechSettings', + 'UpdateEnvironmentRequest', + 'Fulfillment', + 'GetFulfillmentRequest', + 'UpdateFulfillmentRequest', + 'GcsSource', + 'GcsSources', + 'HumanAgentAssistantEvent', + 'BatchDeleteIntentsRequest', + 'BatchUpdateIntentsRequest', + 'BatchUpdateIntentsResponse', + 'CreateIntentRequest', + 'DeleteIntentRequest', + 'GetIntentRequest', + 'Intent', + 'IntentBatch', + 'ListIntentsRequest', + 'ListIntentsResponse', + 'UpdateIntentRequest', + 'IntentView', + 'CreateKnowledgeBaseRequest', + 'DeleteKnowledgeBaseRequest', + 'GetKnowledgeBaseRequest', + 'KnowledgeBase', + 'ListKnowledgeBasesRequest', + 'ListKnowledgeBasesResponse', + 'UpdateKnowledgeBaseRequest', + 'AnalyzeContentRequest', + 'AnalyzeContentResponse', + 'AnnotatedMessagePart', + 'ArticleAnswer', + 'AssistQueryParameters', + 'AutomatedAgentReply', + 'CompileSuggestionRequest', + 'CompileSuggestionResponse', + 'CreateParticipantRequest', + 'DtmfParameters', + 'FaqAnswer', + 'GetParticipantRequest', + 'ListParticipantsRequest', + 'ListParticipantsResponse', + 'ListSuggestionsRequest', + 'ListSuggestionsResponse', + 'Message', + 'MessageAnnotation', + 'OutputAudio', + 'Participant', + 'ResponseMessage', + 'SmartReplyAnswer', + 'SuggestArticlesRequest', + 'SuggestArticlesResponse', + 'SuggestFaqAnswersRequest', + 'SuggestFaqAnswersResponse', + 'Suggestion', + 'SuggestionFeature', + 'SuggestionResult', + 'SuggestSmartRepliesRequest', + 'SuggestSmartRepliesResponse', + 'UpdateParticipantRequest', + 'DetectIntentRequest', + 'DetectIntentResponse', + 'EventInput', + 'KnowledgeAnswers', + 'QueryInput', + 'QueryParameters', + 'QueryResult', + 'Sentiment', + 'SentimentAnalysisRequestConfig', + 'SentimentAnalysisResult', + 'StreamingDetectIntentRequest', + 'StreamingDetectIntentResponse', + 'StreamingRecognitionResult', + 'TextInput', + 'CreateSessionEntityTypeRequest', + 'DeleteSessionEntityTypeRequest', + 'GetSessionEntityTypeRequest', + 'ListSessionEntityTypesRequest', + 'ListSessionEntityTypesResponse', + 'SessionEntityType', + 'UpdateSessionEntityTypeRequest', + 'ValidationError', + 'ValidationResult', + 'CreateVersionRequest', + 'DeleteVersionRequest', + 'GetVersionRequest', + 'ListVersionsRequest', + 'ListVersionsResponse', + 'UpdateVersionRequest', + 'Version', + 'OriginalDetectIntentRequest', + 'WebhookRequest', + 'WebhookResponse', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow/py.typed b/owl-bot-staging/v2beta1/google/cloud/dialogflow/py.typed new file mode 100644 index 000000000..2c6e5af62 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-dialogflow package uses inline types. diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/__init__.py new file mode 100644 index 000000000..6bc3010d3 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/__init__.py @@ -0,0 +1,466 @@ +# -*- 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.agents import AgentsClient +from .services.agents import AgentsAsyncClient +from .services.answer_records import AnswerRecordsClient +from .services.answer_records import AnswerRecordsAsyncClient +from .services.contexts import ContextsClient +from .services.contexts import ContextsAsyncClient +from .services.conversation_profiles import ConversationProfilesClient +from .services.conversation_profiles import ConversationProfilesAsyncClient +from .services.conversations import ConversationsClient +from .services.conversations import ConversationsAsyncClient +from .services.documents import DocumentsClient +from .services.documents import DocumentsAsyncClient +from .services.entity_types import EntityTypesClient +from .services.entity_types import EntityTypesAsyncClient +from .services.environments import EnvironmentsClient +from .services.environments import EnvironmentsAsyncClient +from .services.fulfillments import FulfillmentsClient +from .services.fulfillments import FulfillmentsAsyncClient +from .services.intents import IntentsClient +from .services.intents import IntentsAsyncClient +from .services.knowledge_bases import KnowledgeBasesClient +from .services.knowledge_bases import KnowledgeBasesAsyncClient +from .services.participants import ParticipantsClient +from .services.participants import ParticipantsAsyncClient +from .services.session_entity_types import SessionEntityTypesClient +from .services.session_entity_types import SessionEntityTypesAsyncClient +from .services.sessions import SessionsClient +from .services.sessions import SessionsAsyncClient +from .services.versions import VersionsClient +from .services.versions import VersionsAsyncClient + +from .types.agent import Agent +from .types.agent import DeleteAgentRequest +from .types.agent import ExportAgentRequest +from .types.agent import ExportAgentResponse +from .types.agent import GetAgentRequest +from .types.agent import GetValidationResultRequest +from .types.agent import ImportAgentRequest +from .types.agent import RestoreAgentRequest +from .types.agent import SearchAgentsRequest +from .types.agent import SearchAgentsResponse +from .types.agent import SetAgentRequest +from .types.agent import SubAgent +from .types.agent import TrainAgentRequest +from .types.answer_record import AgentAssistantFeedback +from .types.answer_record import AgentAssistantRecord +from .types.answer_record import AnswerFeedback +from .types.answer_record import AnswerRecord +from .types.answer_record import GetAnswerRecordRequest +from .types.answer_record import ListAnswerRecordsRequest +from .types.answer_record import ListAnswerRecordsResponse +from .types.answer_record import UpdateAnswerRecordRequest +from .types.audio_config import InputAudioConfig +from .types.audio_config import OutputAudioConfig +from .types.audio_config import SpeechContext +from .types.audio_config import SpeechToTextConfig +from .types.audio_config import SpeechWordInfo +from .types.audio_config import SynthesizeSpeechConfig +from .types.audio_config import TelephonyDtmfEvents +from .types.audio_config import VoiceSelectionParams +from .types.audio_config import AudioEncoding +from .types.audio_config import OutputAudioEncoding +from .types.audio_config import SpeechModelVariant +from .types.audio_config import SsmlVoiceGender +from .types.audio_config import TelephonyDtmf +from .types.context import Context +from .types.context import CreateContextRequest +from .types.context import DeleteAllContextsRequest +from .types.context import DeleteContextRequest +from .types.context import GetContextRequest +from .types.context import ListContextsRequest +from .types.context import ListContextsResponse +from .types.context import UpdateContextRequest +from .types.conversation import BatchCreateMessagesRequest +from .types.conversation import BatchCreateMessagesResponse +from .types.conversation import CompleteConversationRequest +from .types.conversation import Conversation +from .types.conversation import ConversationPhoneNumber +from .types.conversation import CreateConversationRequest +from .types.conversation import CreateMessageRequest +from .types.conversation import GetConversationRequest +from .types.conversation import ListConversationsRequest +from .types.conversation import ListConversationsResponse +from .types.conversation import ListMessagesRequest +from .types.conversation import ListMessagesResponse +from .types.conversation_event import ConversationEvent +from .types.conversation_profile import AutomatedAgentConfig +from .types.conversation_profile import ConversationProfile +from .types.conversation_profile import CreateConversationProfileRequest +from .types.conversation_profile import DeleteConversationProfileRequest +from .types.conversation_profile import GetConversationProfileRequest +from .types.conversation_profile import HumanAgentAssistantConfig +from .types.conversation_profile import HumanAgentHandoffConfig +from .types.conversation_profile import ListConversationProfilesRequest +from .types.conversation_profile import ListConversationProfilesResponse +from .types.conversation_profile import LoggingConfig +from .types.conversation_profile import NotificationConfig +from .types.conversation_profile import UpdateConversationProfileRequest +from .types.document import CreateDocumentRequest +from .types.document import DeleteDocumentRequest +from .types.document import Document +from .types.document import GetDocumentRequest +from .types.document import ImportDocumentsRequest +from .types.document import ImportDocumentsResponse +from .types.document import ImportDocumentTemplate +from .types.document import KnowledgeOperationMetadata +from .types.document import ListDocumentsRequest +from .types.document import ListDocumentsResponse +from .types.document import ReloadDocumentRequest +from .types.document import UpdateDocumentRequest +from .types.entity_type import BatchCreateEntitiesRequest +from .types.entity_type import BatchDeleteEntitiesRequest +from .types.entity_type import BatchDeleteEntityTypesRequest +from .types.entity_type import BatchUpdateEntitiesRequest +from .types.entity_type import BatchUpdateEntityTypesRequest +from .types.entity_type import BatchUpdateEntityTypesResponse +from .types.entity_type import CreateEntityTypeRequest +from .types.entity_type import DeleteEntityTypeRequest +from .types.entity_type import EntityType +from .types.entity_type import EntityTypeBatch +from .types.entity_type import GetEntityTypeRequest +from .types.entity_type import ListEntityTypesRequest +from .types.entity_type import ListEntityTypesResponse +from .types.entity_type import UpdateEntityTypeRequest +from .types.environment import CreateEnvironmentRequest +from .types.environment import DeleteEnvironmentRequest +from .types.environment import Environment +from .types.environment import EnvironmentHistory +from .types.environment import GetEnvironmentHistoryRequest +from .types.environment import GetEnvironmentRequest +from .types.environment import ListEnvironmentsRequest +from .types.environment import ListEnvironmentsResponse +from .types.environment import TextToSpeechSettings +from .types.environment import UpdateEnvironmentRequest +from .types.fulfillment import Fulfillment +from .types.fulfillment import GetFulfillmentRequest +from .types.fulfillment import UpdateFulfillmentRequest +from .types.gcs import GcsSource +from .types.gcs import GcsSources +from .types.human_agent_assistant_event import HumanAgentAssistantEvent +from .types.intent import BatchDeleteIntentsRequest +from .types.intent import BatchUpdateIntentsRequest +from .types.intent import BatchUpdateIntentsResponse +from .types.intent import CreateIntentRequest +from .types.intent import DeleteIntentRequest +from .types.intent import GetIntentRequest +from .types.intent import Intent +from .types.intent import IntentBatch +from .types.intent import ListIntentsRequest +from .types.intent import ListIntentsResponse +from .types.intent import UpdateIntentRequest +from .types.intent import IntentView +from .types.knowledge_base import CreateKnowledgeBaseRequest +from .types.knowledge_base import DeleteKnowledgeBaseRequest +from .types.knowledge_base import GetKnowledgeBaseRequest +from .types.knowledge_base import KnowledgeBase +from .types.knowledge_base import ListKnowledgeBasesRequest +from .types.knowledge_base import ListKnowledgeBasesResponse +from .types.knowledge_base import UpdateKnowledgeBaseRequest +from .types.participant import AnalyzeContentRequest +from .types.participant import AnalyzeContentResponse +from .types.participant import AnnotatedMessagePart +from .types.participant import ArticleAnswer +from .types.participant import AssistQueryParameters +from .types.participant import AutomatedAgentReply +from .types.participant import CompileSuggestionRequest +from .types.participant import CompileSuggestionResponse +from .types.participant import CreateParticipantRequest +from .types.participant import DtmfParameters +from .types.participant import FaqAnswer +from .types.participant import GetParticipantRequest +from .types.participant import ListParticipantsRequest +from .types.participant import ListParticipantsResponse +from .types.participant import ListSuggestionsRequest +from .types.participant import ListSuggestionsResponse +from .types.participant import Message +from .types.participant import MessageAnnotation +from .types.participant import OutputAudio +from .types.participant import Participant +from .types.participant import ResponseMessage +from .types.participant import SmartReplyAnswer +from .types.participant import SuggestArticlesRequest +from .types.participant import SuggestArticlesResponse +from .types.participant import SuggestFaqAnswersRequest +from .types.participant import SuggestFaqAnswersResponse +from .types.participant import Suggestion +from .types.participant import SuggestionFeature +from .types.participant import SuggestionResult +from .types.participant import SuggestSmartRepliesRequest +from .types.participant import SuggestSmartRepliesResponse +from .types.participant import UpdateParticipantRequest +from .types.session import DetectIntentRequest +from .types.session import DetectIntentResponse +from .types.session import EventInput +from .types.session import KnowledgeAnswers +from .types.session import QueryInput +from .types.session import QueryParameters +from .types.session import QueryResult +from .types.session import Sentiment +from .types.session import SentimentAnalysisRequestConfig +from .types.session import SentimentAnalysisResult +from .types.session import StreamingDetectIntentRequest +from .types.session import StreamingDetectIntentResponse +from .types.session import StreamingRecognitionResult +from .types.session import TextInput +from .types.session_entity_type import CreateSessionEntityTypeRequest +from .types.session_entity_type import DeleteSessionEntityTypeRequest +from .types.session_entity_type import GetSessionEntityTypeRequest +from .types.session_entity_type import ListSessionEntityTypesRequest +from .types.session_entity_type import ListSessionEntityTypesResponse +from .types.session_entity_type import SessionEntityType +from .types.session_entity_type import UpdateSessionEntityTypeRequest +from .types.validation_result import ValidationError +from .types.validation_result import ValidationResult +from .types.version import CreateVersionRequest +from .types.version import DeleteVersionRequest +from .types.version import GetVersionRequest +from .types.version import ListVersionsRequest +from .types.version import ListVersionsResponse +from .types.version import UpdateVersionRequest +from .types.version import Version +from .types.webhook import OriginalDetectIntentRequest +from .types.webhook import WebhookRequest +from .types.webhook import WebhookResponse + +__all__ = ( + 'AgentsAsyncClient', + 'AnswerRecordsAsyncClient', + 'ContextsAsyncClient', + 'ConversationProfilesAsyncClient', + 'ConversationsAsyncClient', + 'DocumentsAsyncClient', + 'EntityTypesAsyncClient', + 'EnvironmentsAsyncClient', + 'FulfillmentsAsyncClient', + 'IntentsAsyncClient', + 'KnowledgeBasesAsyncClient', + 'ParticipantsAsyncClient', + 'SessionEntityTypesAsyncClient', + 'SessionsAsyncClient', + 'VersionsAsyncClient', +'Agent', +'AgentAssistantFeedback', +'AgentAssistantRecord', +'AgentsClient', +'AnalyzeContentRequest', +'AnalyzeContentResponse', +'AnnotatedMessagePart', +'AnswerFeedback', +'AnswerRecord', +'AnswerRecordsClient', +'ArticleAnswer', +'AssistQueryParameters', +'AudioEncoding', +'AutomatedAgentConfig', +'AutomatedAgentReply', +'BatchCreateEntitiesRequest', +'BatchCreateMessagesRequest', +'BatchCreateMessagesResponse', +'BatchDeleteEntitiesRequest', +'BatchDeleteEntityTypesRequest', +'BatchDeleteIntentsRequest', +'BatchUpdateEntitiesRequest', +'BatchUpdateEntityTypesRequest', +'BatchUpdateEntityTypesResponse', +'BatchUpdateIntentsRequest', +'BatchUpdateIntentsResponse', +'CompileSuggestionRequest', +'CompileSuggestionResponse', +'CompleteConversationRequest', +'Context', +'ContextsClient', +'Conversation', +'ConversationEvent', +'ConversationPhoneNumber', +'ConversationProfile', +'ConversationProfilesClient', +'ConversationsClient', +'CreateContextRequest', +'CreateConversationProfileRequest', +'CreateConversationRequest', +'CreateDocumentRequest', +'CreateEntityTypeRequest', +'CreateEnvironmentRequest', +'CreateIntentRequest', +'CreateKnowledgeBaseRequest', +'CreateMessageRequest', +'CreateParticipantRequest', +'CreateSessionEntityTypeRequest', +'CreateVersionRequest', +'DeleteAgentRequest', +'DeleteAllContextsRequest', +'DeleteContextRequest', +'DeleteConversationProfileRequest', +'DeleteDocumentRequest', +'DeleteEntityTypeRequest', +'DeleteEnvironmentRequest', +'DeleteIntentRequest', +'DeleteKnowledgeBaseRequest', +'DeleteSessionEntityTypeRequest', +'DeleteVersionRequest', +'DetectIntentRequest', +'DetectIntentResponse', +'Document', +'DocumentsClient', +'DtmfParameters', +'EntityType', +'EntityTypeBatch', +'EntityTypesClient', +'Environment', +'EnvironmentHistory', +'EnvironmentsClient', +'EventInput', +'ExportAgentRequest', +'ExportAgentResponse', +'FaqAnswer', +'Fulfillment', +'FulfillmentsClient', +'GcsSource', +'GcsSources', +'GetAgentRequest', +'GetAnswerRecordRequest', +'GetContextRequest', +'GetConversationProfileRequest', +'GetConversationRequest', +'GetDocumentRequest', +'GetEntityTypeRequest', +'GetEnvironmentHistoryRequest', +'GetEnvironmentRequest', +'GetFulfillmentRequest', +'GetIntentRequest', +'GetKnowledgeBaseRequest', +'GetParticipantRequest', +'GetSessionEntityTypeRequest', +'GetValidationResultRequest', +'GetVersionRequest', +'HumanAgentAssistantConfig', +'HumanAgentAssistantEvent', +'HumanAgentHandoffConfig', +'ImportAgentRequest', +'ImportDocumentTemplate', +'ImportDocumentsRequest', +'ImportDocumentsResponse', +'InputAudioConfig', +'Intent', +'IntentBatch', +'IntentView', +'IntentsClient', +'KnowledgeAnswers', +'KnowledgeBase', +'KnowledgeBasesClient', +'KnowledgeOperationMetadata', +'ListAnswerRecordsRequest', +'ListAnswerRecordsResponse', +'ListContextsRequest', +'ListContextsResponse', +'ListConversationProfilesRequest', +'ListConversationProfilesResponse', +'ListConversationsRequest', +'ListConversationsResponse', +'ListDocumentsRequest', +'ListDocumentsResponse', +'ListEntityTypesRequest', +'ListEntityTypesResponse', +'ListEnvironmentsRequest', +'ListEnvironmentsResponse', +'ListIntentsRequest', +'ListIntentsResponse', +'ListKnowledgeBasesRequest', +'ListKnowledgeBasesResponse', +'ListMessagesRequest', +'ListMessagesResponse', +'ListParticipantsRequest', +'ListParticipantsResponse', +'ListSessionEntityTypesRequest', +'ListSessionEntityTypesResponse', +'ListSuggestionsRequest', +'ListSuggestionsResponse', +'ListVersionsRequest', +'ListVersionsResponse', +'LoggingConfig', +'Message', +'MessageAnnotation', +'NotificationConfig', +'OriginalDetectIntentRequest', +'OutputAudio', +'OutputAudioConfig', +'OutputAudioEncoding', +'Participant', +'ParticipantsClient', +'QueryInput', +'QueryParameters', +'QueryResult', +'ReloadDocumentRequest', +'ResponseMessage', +'RestoreAgentRequest', +'SearchAgentsRequest', +'SearchAgentsResponse', +'Sentiment', +'SentimentAnalysisRequestConfig', +'SentimentAnalysisResult', +'SessionEntityType', +'SessionEntityTypesClient', +'SessionsClient', +'SetAgentRequest', +'SmartReplyAnswer', +'SpeechContext', +'SpeechModelVariant', +'SpeechToTextConfig', +'SpeechWordInfo', +'SsmlVoiceGender', +'StreamingDetectIntentRequest', +'StreamingDetectIntentResponse', +'StreamingRecognitionResult', +'SubAgent', +'SuggestArticlesRequest', +'SuggestArticlesResponse', +'SuggestFaqAnswersRequest', +'SuggestFaqAnswersResponse', +'SuggestSmartRepliesRequest', +'SuggestSmartRepliesResponse', +'Suggestion', +'SuggestionFeature', +'SuggestionResult', +'SynthesizeSpeechConfig', +'TelephonyDtmf', +'TelephonyDtmfEvents', +'TextInput', +'TextToSpeechSettings', +'TrainAgentRequest', +'UpdateAnswerRecordRequest', +'UpdateContextRequest', +'UpdateConversationProfileRequest', +'UpdateDocumentRequest', +'UpdateEntityTypeRequest', +'UpdateEnvironmentRequest', +'UpdateFulfillmentRequest', +'UpdateIntentRequest', +'UpdateKnowledgeBaseRequest', +'UpdateParticipantRequest', +'UpdateSessionEntityTypeRequest', +'UpdateVersionRequest', +'ValidationError', +'ValidationResult', +'Version', +'VersionsClient', +'VoiceSelectionParams', +'WebhookRequest', +'WebhookResponse', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/gapic_metadata.json b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/gapic_metadata.json new file mode 100644 index 000000000..ed94b0a54 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/gapic_metadata.json @@ -0,0 +1,1099 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.dialogflow_v2beta1", + "protoPackage": "google.cloud.dialogflow.v2beta1", + "schema": "1.0", + "services": { + "Agents": { + "clients": { + "grpc": { + "libraryClient": "AgentsClient", + "rpcs": { + "DeleteAgent": { + "methods": [ + "delete_agent" + ] + }, + "ExportAgent": { + "methods": [ + "export_agent" + ] + }, + "GetAgent": { + "methods": [ + "get_agent" + ] + }, + "GetValidationResult": { + "methods": [ + "get_validation_result" + ] + }, + "ImportAgent": { + "methods": [ + "import_agent" + ] + }, + "RestoreAgent": { + "methods": [ + "restore_agent" + ] + }, + "SearchAgents": { + "methods": [ + "search_agents" + ] + }, + "SetAgent": { + "methods": [ + "set_agent" + ] + }, + "TrainAgent": { + "methods": [ + "train_agent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AgentsAsyncClient", + "rpcs": { + "DeleteAgent": { + "methods": [ + "delete_agent" + ] + }, + "ExportAgent": { + "methods": [ + "export_agent" + ] + }, + "GetAgent": { + "methods": [ + "get_agent" + ] + }, + "GetValidationResult": { + "methods": [ + "get_validation_result" + ] + }, + "ImportAgent": { + "methods": [ + "import_agent" + ] + }, + "RestoreAgent": { + "methods": [ + "restore_agent" + ] + }, + "SearchAgents": { + "methods": [ + "search_agents" + ] + }, + "SetAgent": { + "methods": [ + "set_agent" + ] + }, + "TrainAgent": { + "methods": [ + "train_agent" + ] + } + } + } + } + }, + "AnswerRecords": { + "clients": { + "grpc": { + "libraryClient": "AnswerRecordsClient", + "rpcs": { + "GetAnswerRecord": { + "methods": [ + "get_answer_record" + ] + }, + "ListAnswerRecords": { + "methods": [ + "list_answer_records" + ] + }, + "UpdateAnswerRecord": { + "methods": [ + "update_answer_record" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AnswerRecordsAsyncClient", + "rpcs": { + "GetAnswerRecord": { + "methods": [ + "get_answer_record" + ] + }, + "ListAnswerRecords": { + "methods": [ + "list_answer_records" + ] + }, + "UpdateAnswerRecord": { + "methods": [ + "update_answer_record" + ] + } + } + } + } + }, + "Contexts": { + "clients": { + "grpc": { + "libraryClient": "ContextsClient", + "rpcs": { + "CreateContext": { + "methods": [ + "create_context" + ] + }, + "DeleteAllContexts": { + "methods": [ + "delete_all_contexts" + ] + }, + "DeleteContext": { + "methods": [ + "delete_context" + ] + }, + "GetContext": { + "methods": [ + "get_context" + ] + }, + "ListContexts": { + "methods": [ + "list_contexts" + ] + }, + "UpdateContext": { + "methods": [ + "update_context" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ContextsAsyncClient", + "rpcs": { + "CreateContext": { + "methods": [ + "create_context" + ] + }, + "DeleteAllContexts": { + "methods": [ + "delete_all_contexts" + ] + }, + "DeleteContext": { + "methods": [ + "delete_context" + ] + }, + "GetContext": { + "methods": [ + "get_context" + ] + }, + "ListContexts": { + "methods": [ + "list_contexts" + ] + }, + "UpdateContext": { + "methods": [ + "update_context" + ] + } + } + } + } + }, + "ConversationProfiles": { + "clients": { + "grpc": { + "libraryClient": "ConversationProfilesClient", + "rpcs": { + "CreateConversationProfile": { + "methods": [ + "create_conversation_profile" + ] + }, + "DeleteConversationProfile": { + "methods": [ + "delete_conversation_profile" + ] + }, + "GetConversationProfile": { + "methods": [ + "get_conversation_profile" + ] + }, + "ListConversationProfiles": { + "methods": [ + "list_conversation_profiles" + ] + }, + "UpdateConversationProfile": { + "methods": [ + "update_conversation_profile" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ConversationProfilesAsyncClient", + "rpcs": { + "CreateConversationProfile": { + "methods": [ + "create_conversation_profile" + ] + }, + "DeleteConversationProfile": { + "methods": [ + "delete_conversation_profile" + ] + }, + "GetConversationProfile": { + "methods": [ + "get_conversation_profile" + ] + }, + "ListConversationProfiles": { + "methods": [ + "list_conversation_profiles" + ] + }, + "UpdateConversationProfile": { + "methods": [ + "update_conversation_profile" + ] + } + } + } + } + }, + "Conversations": { + "clients": { + "grpc": { + "libraryClient": "ConversationsClient", + "rpcs": { + "BatchCreateMessages": { + "methods": [ + "batch_create_messages" + ] + }, + "CompleteConversation": { + "methods": [ + "complete_conversation" + ] + }, + "CreateConversation": { + "methods": [ + "create_conversation" + ] + }, + "GetConversation": { + "methods": [ + "get_conversation" + ] + }, + "ListConversations": { + "methods": [ + "list_conversations" + ] + }, + "ListMessages": { + "methods": [ + "list_messages" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ConversationsAsyncClient", + "rpcs": { + "BatchCreateMessages": { + "methods": [ + "batch_create_messages" + ] + }, + "CompleteConversation": { + "methods": [ + "complete_conversation" + ] + }, + "CreateConversation": { + "methods": [ + "create_conversation" + ] + }, + "GetConversation": { + "methods": [ + "get_conversation" + ] + }, + "ListConversations": { + "methods": [ + "list_conversations" + ] + }, + "ListMessages": { + "methods": [ + "list_messages" + ] + } + } + } + } + }, + "Documents": { + "clients": { + "grpc": { + "libraryClient": "DocumentsClient", + "rpcs": { + "CreateDocument": { + "methods": [ + "create_document" + ] + }, + "DeleteDocument": { + "methods": [ + "delete_document" + ] + }, + "GetDocument": { + "methods": [ + "get_document" + ] + }, + "ImportDocuments": { + "methods": [ + "import_documents" + ] + }, + "ListDocuments": { + "methods": [ + "list_documents" + ] + }, + "ReloadDocument": { + "methods": [ + "reload_document" + ] + }, + "UpdateDocument": { + "methods": [ + "update_document" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DocumentsAsyncClient", + "rpcs": { + "CreateDocument": { + "methods": [ + "create_document" + ] + }, + "DeleteDocument": { + "methods": [ + "delete_document" + ] + }, + "GetDocument": { + "methods": [ + "get_document" + ] + }, + "ImportDocuments": { + "methods": [ + "import_documents" + ] + }, + "ListDocuments": { + "methods": [ + "list_documents" + ] + }, + "ReloadDocument": { + "methods": [ + "reload_document" + ] + }, + "UpdateDocument": { + "methods": [ + "update_document" + ] + } + } + } + } + }, + "EntityTypes": { + "clients": { + "grpc": { + "libraryClient": "EntityTypesClient", + "rpcs": { + "BatchCreateEntities": { + "methods": [ + "batch_create_entities" + ] + }, + "BatchDeleteEntities": { + "methods": [ + "batch_delete_entities" + ] + }, + "BatchDeleteEntityTypes": { + "methods": [ + "batch_delete_entity_types" + ] + }, + "BatchUpdateEntities": { + "methods": [ + "batch_update_entities" + ] + }, + "BatchUpdateEntityTypes": { + "methods": [ + "batch_update_entity_types" + ] + }, + "CreateEntityType": { + "methods": [ + "create_entity_type" + ] + }, + "DeleteEntityType": { + "methods": [ + "delete_entity_type" + ] + }, + "GetEntityType": { + "methods": [ + "get_entity_type" + ] + }, + "ListEntityTypes": { + "methods": [ + "list_entity_types" + ] + }, + "UpdateEntityType": { + "methods": [ + "update_entity_type" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EntityTypesAsyncClient", + "rpcs": { + "BatchCreateEntities": { + "methods": [ + "batch_create_entities" + ] + }, + "BatchDeleteEntities": { + "methods": [ + "batch_delete_entities" + ] + }, + "BatchDeleteEntityTypes": { + "methods": [ + "batch_delete_entity_types" + ] + }, + "BatchUpdateEntities": { + "methods": [ + "batch_update_entities" + ] + }, + "BatchUpdateEntityTypes": { + "methods": [ + "batch_update_entity_types" + ] + }, + "CreateEntityType": { + "methods": [ + "create_entity_type" + ] + }, + "DeleteEntityType": { + "methods": [ + "delete_entity_type" + ] + }, + "GetEntityType": { + "methods": [ + "get_entity_type" + ] + }, + "ListEntityTypes": { + "methods": [ + "list_entity_types" + ] + }, + "UpdateEntityType": { + "methods": [ + "update_entity_type" + ] + } + } + } + } + }, + "Environments": { + "clients": { + "grpc": { + "libraryClient": "EnvironmentsClient", + "rpcs": { + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "GetEnvironmentHistory": { + "methods": [ + "get_environment_history" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EnvironmentsAsyncClient", + "rpcs": { + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "GetEnvironmentHistory": { + "methods": [ + "get_environment_history" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + } + } + }, + "Fulfillments": { + "clients": { + "grpc": { + "libraryClient": "FulfillmentsClient", + "rpcs": { + "GetFulfillment": { + "methods": [ + "get_fulfillment" + ] + }, + "UpdateFulfillment": { + "methods": [ + "update_fulfillment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "FulfillmentsAsyncClient", + "rpcs": { + "GetFulfillment": { + "methods": [ + "get_fulfillment" + ] + }, + "UpdateFulfillment": { + "methods": [ + "update_fulfillment" + ] + } + } + } + } + }, + "Intents": { + "clients": { + "grpc": { + "libraryClient": "IntentsClient", + "rpcs": { + "BatchDeleteIntents": { + "methods": [ + "batch_delete_intents" + ] + }, + "BatchUpdateIntents": { + "methods": [ + "batch_update_intents" + ] + }, + "CreateIntent": { + "methods": [ + "create_intent" + ] + }, + "DeleteIntent": { + "methods": [ + "delete_intent" + ] + }, + "GetIntent": { + "methods": [ + "get_intent" + ] + }, + "ListIntents": { + "methods": [ + "list_intents" + ] + }, + "UpdateIntent": { + "methods": [ + "update_intent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "IntentsAsyncClient", + "rpcs": { + "BatchDeleteIntents": { + "methods": [ + "batch_delete_intents" + ] + }, + "BatchUpdateIntents": { + "methods": [ + "batch_update_intents" + ] + }, + "CreateIntent": { + "methods": [ + "create_intent" + ] + }, + "DeleteIntent": { + "methods": [ + "delete_intent" + ] + }, + "GetIntent": { + "methods": [ + "get_intent" + ] + }, + "ListIntents": { + "methods": [ + "list_intents" + ] + }, + "UpdateIntent": { + "methods": [ + "update_intent" + ] + } + } + } + } + }, + "KnowledgeBases": { + "clients": { + "grpc": { + "libraryClient": "KnowledgeBasesClient", + "rpcs": { + "CreateKnowledgeBase": { + "methods": [ + "create_knowledge_base" + ] + }, + "DeleteKnowledgeBase": { + "methods": [ + "delete_knowledge_base" + ] + }, + "GetKnowledgeBase": { + "methods": [ + "get_knowledge_base" + ] + }, + "ListKnowledgeBases": { + "methods": [ + "list_knowledge_bases" + ] + }, + "UpdateKnowledgeBase": { + "methods": [ + "update_knowledge_base" + ] + } + } + }, + "grpc-async": { + "libraryClient": "KnowledgeBasesAsyncClient", + "rpcs": { + "CreateKnowledgeBase": { + "methods": [ + "create_knowledge_base" + ] + }, + "DeleteKnowledgeBase": { + "methods": [ + "delete_knowledge_base" + ] + }, + "GetKnowledgeBase": { + "methods": [ + "get_knowledge_base" + ] + }, + "ListKnowledgeBases": { + "methods": [ + "list_knowledge_bases" + ] + }, + "UpdateKnowledgeBase": { + "methods": [ + "update_knowledge_base" + ] + } + } + } + } + }, + "Participants": { + "clients": { + "grpc": { + "libraryClient": "ParticipantsClient", + "rpcs": { + "AnalyzeContent": { + "methods": [ + "analyze_content" + ] + }, + "CompileSuggestion": { + "methods": [ + "compile_suggestion" + ] + }, + "CreateParticipant": { + "methods": [ + "create_participant" + ] + }, + "GetParticipant": { + "methods": [ + "get_participant" + ] + }, + "ListParticipants": { + "methods": [ + "list_participants" + ] + }, + "ListSuggestions": { + "methods": [ + "list_suggestions" + ] + }, + "SuggestArticles": { + "methods": [ + "suggest_articles" + ] + }, + "SuggestFaqAnswers": { + "methods": [ + "suggest_faq_answers" + ] + }, + "SuggestSmartReplies": { + "methods": [ + "suggest_smart_replies" + ] + }, + "UpdateParticipant": { + "methods": [ + "update_participant" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ParticipantsAsyncClient", + "rpcs": { + "AnalyzeContent": { + "methods": [ + "analyze_content" + ] + }, + "CompileSuggestion": { + "methods": [ + "compile_suggestion" + ] + }, + "CreateParticipant": { + "methods": [ + "create_participant" + ] + }, + "GetParticipant": { + "methods": [ + "get_participant" + ] + }, + "ListParticipants": { + "methods": [ + "list_participants" + ] + }, + "ListSuggestions": { + "methods": [ + "list_suggestions" + ] + }, + "SuggestArticles": { + "methods": [ + "suggest_articles" + ] + }, + "SuggestFaqAnswers": { + "methods": [ + "suggest_faq_answers" + ] + }, + "SuggestSmartReplies": { + "methods": [ + "suggest_smart_replies" + ] + }, + "UpdateParticipant": { + "methods": [ + "update_participant" + ] + } + } + } + } + }, + "SessionEntityTypes": { + "clients": { + "grpc": { + "libraryClient": "SessionEntityTypesClient", + "rpcs": { + "CreateSessionEntityType": { + "methods": [ + "create_session_entity_type" + ] + }, + "DeleteSessionEntityType": { + "methods": [ + "delete_session_entity_type" + ] + }, + "GetSessionEntityType": { + "methods": [ + "get_session_entity_type" + ] + }, + "ListSessionEntityTypes": { + "methods": [ + "list_session_entity_types" + ] + }, + "UpdateSessionEntityType": { + "methods": [ + "update_session_entity_type" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SessionEntityTypesAsyncClient", + "rpcs": { + "CreateSessionEntityType": { + "methods": [ + "create_session_entity_type" + ] + }, + "DeleteSessionEntityType": { + "methods": [ + "delete_session_entity_type" + ] + }, + "GetSessionEntityType": { + "methods": [ + "get_session_entity_type" + ] + }, + "ListSessionEntityTypes": { + "methods": [ + "list_session_entity_types" + ] + }, + "UpdateSessionEntityType": { + "methods": [ + "update_session_entity_type" + ] + } + } + } + } + }, + "Sessions": { + "clients": { + "grpc": { + "libraryClient": "SessionsClient", + "rpcs": { + "DetectIntent": { + "methods": [ + "detect_intent" + ] + }, + "StreamingDetectIntent": { + "methods": [ + "streaming_detect_intent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SessionsAsyncClient", + "rpcs": { + "DetectIntent": { + "methods": [ + "detect_intent" + ] + }, + "StreamingDetectIntent": { + "methods": [ + "streaming_detect_intent" + ] + } + } + } + } + }, + "Versions": { + "clients": { + "grpc": { + "libraryClient": "VersionsClient", + "rpcs": { + "CreateVersion": { + "methods": [ + "create_version" + ] + }, + "DeleteVersion": { + "methods": [ + "delete_version" + ] + }, + "GetVersion": { + "methods": [ + "get_version" + ] + }, + "ListVersions": { + "methods": [ + "list_versions" + ] + }, + "UpdateVersion": { + "methods": [ + "update_version" + ] + } + } + }, + "grpc-async": { + "libraryClient": "VersionsAsyncClient", + "rpcs": { + "CreateVersion": { + "methods": [ + "create_version" + ] + }, + "DeleteVersion": { + "methods": [ + "delete_version" + ] + }, + "GetVersion": { + "methods": [ + "get_version" + ] + }, + "ListVersions": { + "methods": [ + "list_versions" + ] + }, + "UpdateVersion": { + "methods": [ + "update_version" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/py.typed b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/py.typed new file mode 100644 index 000000000..2c6e5af62 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-dialogflow package uses inline types. diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/__init__.py new file mode 100644 index 000000000..4de65971c --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/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/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/__init__.py new file mode 100644 index 000000000..057c8b80b --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/__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 AgentsClient +from .async_client import AgentsAsyncClient + +__all__ = ( + 'AgentsClient', + 'AgentsAsyncClient', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/async_client.py new file mode 100644 index 000000000..491763498 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/async_client.py @@ -0,0 +1,983 @@ +# -*- 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 + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.dialogflow_v2beta1.services.agents import pagers +from google.cloud.dialogflow_v2beta1.types import agent +from google.cloud.dialogflow_v2beta1.types import agent as gcd_agent +from google.cloud.dialogflow_v2beta1.types import validation_result +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import AgentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AgentsGrpcAsyncIOTransport +from .client import AgentsClient + + +class AgentsAsyncClient: + """Service for managing + [Agents][google.cloud.dialogflow.v2beta1.Agent]. + """ + + _client: AgentsClient + + DEFAULT_ENDPOINT = AgentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AgentsClient.DEFAULT_MTLS_ENDPOINT + + agent_path = staticmethod(AgentsClient.agent_path) + parse_agent_path = staticmethod(AgentsClient.parse_agent_path) + common_billing_account_path = staticmethod(AgentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AgentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AgentsClient.common_folder_path) + parse_common_folder_path = staticmethod(AgentsClient.parse_common_folder_path) + common_organization_path = staticmethod(AgentsClient.common_organization_path) + parse_common_organization_path = staticmethod(AgentsClient.parse_common_organization_path) + common_project_path = staticmethod(AgentsClient.common_project_path) + parse_common_project_path = staticmethod(AgentsClient.parse_common_project_path) + common_location_path = staticmethod(AgentsClient.common_location_path) + parse_common_location_path = staticmethod(AgentsClient.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: + AgentsAsyncClient: The constructed client. + """ + return AgentsClient.from_service_account_info.__func__(AgentsAsyncClient, 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: + AgentsAsyncClient: The constructed client. + """ + return AgentsClient.from_service_account_file.__func__(AgentsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> AgentsTransport: + """Returns the transport used by the client instance. + + Returns: + AgentsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(AgentsClient).get_transport_class, type(AgentsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, AgentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the agents 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, ~.AgentsTransport]): 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 = AgentsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_agent(self, + request: Union[agent.GetAgentRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> agent.Agent: + r"""Retrieves the specified agent. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetAgentRequest, dict]): + The request object. The request message for + [Agents.GetAgent][google.cloud.dialogflow.v2beta1.Agents.GetAgent]. + parent (:class:`str`): + Required. The project that the agent to fetch is + associated with. Format: ``projects/`` or + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Agent: + A Dialogflow agent is a virtual agent that handles conversations with your + end-users. It is a natural language understanding + module that understands the nuances of human + language. Dialogflow translates end-user text or + audio during a conversation to structured data that + your apps and services can understand. You design and + build a Dialogflow agent to handle the types of + conversations required for your system. + + For more information about agents, see the [Agent + guide](\ https://cloud.google.com/dialogflow/docs/agents-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is 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 = agent.GetAgentRequest(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.get_agent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_agent(self, + request: Union[gcd_agent.SetAgentRequest, dict] = None, + *, + agent: gcd_agent.Agent = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_agent.Agent: + r"""Creates/updates the specified agent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.SetAgentRequest, dict]): + The request object. The request message for + [Agents.SetAgent][google.cloud.dialogflow.v2beta1.Agents.SetAgent]. + agent (:class:`google.cloud.dialogflow_v2beta1.types.Agent`): + Required. The agent to update. + This corresponds to the ``agent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Agent: + A Dialogflow agent is a virtual agent that handles conversations with your + end-users. It is a natural language understanding + module that understands the nuances of human + language. Dialogflow translates end-user text or + audio during a conversation to structured data that + your apps and services can understand. You design and + build a Dialogflow agent to handle the types of + conversations required for your system. + + For more information about agents, see the [Agent + guide](\ https://cloud.google.com/dialogflow/docs/agents-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([agent]) + if request is 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 = gcd_agent.SetAgentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if agent is not None: + request.agent = agent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_agent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("agent.parent", request.agent.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_agent(self, + request: Union[agent.DeleteAgentRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified agent. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.DeleteAgentRequest, dict]): + The request object. The request message for + [Agents.DeleteAgent][google.cloud.dialogflow.v2beta1.Agents.DeleteAgent]. + parent (:class:`str`): + Required. The project that the agent to delete is + associated with. Format: ``projects/`` or + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # 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 = agent.DeleteAgentRequest(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.delete_agent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def search_agents(self, + request: Union[agent.SearchAgentsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAgentsAsyncPager: + r"""Returns the list of agents. Since there is at most one + conversational agent per project, this method is useful + primarily for listing all agents across projects the caller has + access to. One can achieve that with a wildcard project + collection id "-". Refer to `List + Sub-Collections `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.SearchAgentsRequest, dict]): + The request object. The request message for + [Agents.SearchAgents][google.cloud.dialogflow.v2beta1.Agents.SearchAgents]. + parent (:class:`str`): + Required. The project to list agents from. Format: + ``projects/`` or + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.services.agents.pagers.SearchAgentsAsyncPager: + The response message for + [Agents.SearchAgents][google.cloud.dialogflow.v2beta1.Agents.SearchAgents]. + + 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 = agent.SearchAgentsRequest(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.search_agents, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.SearchAgentsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def train_agent(self, + request: Union[agent.TrainAgentRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Trains the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.TrainAgentRequest, dict]): + The request object. The request message for + [Agents.TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent]. + parent (:class:`str`): + Required. The project that the agent to train is + associated with. Format: ``projects/`` or + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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 = agent.TrainAgentRequest(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.train_agent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def export_agent(self, + request: Union[agent.ExportAgentRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Exports the specified agent to a ZIP file. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ExportAgentResponse][google.cloud.dialogflow.v2beta1.ExportAgentResponse] + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ExportAgentRequest, dict]): + The request object. The request message for + [Agents.ExportAgent][google.cloud.dialogflow.v2beta1.Agents.ExportAgent]. + parent (:class:`str`): + Required. The project that the agent to export is + associated with. Format: ``projects/`` or + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflow_v2beta1.types.ExportAgentResponse` + The response message for + [Agents.ExportAgent][google.cloud.dialogflow.v2beta1.Agents.ExportAgent]. + + """ + # 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 = agent.ExportAgentRequest(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.export_agent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + agent.ExportAgentResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def import_agent(self, + request: Union[agent.ImportAgentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Imports the specified agent from a ZIP file. + + Uploads new intents and entity types without deleting the + existing ones. Intents and entity types with the same name are + replaced with the new versions from + [ImportAgentRequest][google.cloud.dialogflow.v2beta1.ImportAgentRequest]. + After the import, the imported draft agent will be trained + automatically (unless disabled in agent settings). However, once + the import is done, training may not be completed yet. Please + call + [TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent] + and wait for the operation it returns in order to train + explicitly. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + The operation only tracks when importing is complete, not when + it is done training. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ImportAgentRequest, dict]): + The request object. The request message for + [Agents.ImportAgent][google.cloud.dialogflow.v2beta1.Agents.ImportAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + request = agent.ImportAgentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_agent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def restore_agent(self, + request: Union[agent.RestoreAgentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Restores the specified agent from a ZIP file. + + Replaces the current agent version with a new one. All the + intents and entity types in the older version are deleted. After + the restore, the restored draft agent will be trained + automatically (unless disabled in agent settings). However, once + the restore is done, training may not be completed yet. Please + call + [TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent] + and wait for the operation it returns in order to train + explicitly. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + The operation only tracks when restoring is complete, not when + it is done training. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.RestoreAgentRequest, dict]): + The request object. The request message for + [Agents.RestoreAgent][google.cloud.dialogflow.v2beta1.Agents.RestoreAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + request = agent.RestoreAgentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.restore_agent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def get_validation_result(self, + request: Union[agent.GetValidationResultRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> validation_result.ValidationResult: + r"""Gets agent validation result. Agent validation is + performed during training time and is updated + automatically when training is completed. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetValidationResultRequest, dict]): + The request object. The request message for + [Agents.GetValidationResult][google.cloud.dialogflow.v2beta1.Agents.GetValidationResult]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.ValidationResult: + Represents the output of agent + validation. + + """ + # Create or coerce a protobuf request object. + request = agent.GetValidationResultRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_validation_result, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "AgentsAsyncClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/client.py new file mode 100644 index 000000000..7326f231f --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/client.py @@ -0,0 +1,1184 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.dialogflow_v2beta1.services.agents import pagers +from google.cloud.dialogflow_v2beta1.types import agent +from google.cloud.dialogflow_v2beta1.types import agent as gcd_agent +from google.cloud.dialogflow_v2beta1.types import validation_result +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import AgentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AgentsGrpcTransport +from .transports.grpc_asyncio import AgentsGrpcAsyncIOTransport + + +class AgentsClientMeta(type): + """Metaclass for the Agents 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[AgentsTransport]] + _transport_registry["grpc"] = AgentsGrpcTransport + _transport_registry["grpc_asyncio"] = AgentsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[AgentsTransport]: + """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 AgentsClient(metaclass=AgentsClientMeta): + """Service for managing + [Agents][google.cloud.dialogflow.v2beta1.Agent]. + """ + + @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 = "dialogflow.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: + AgentsClient: 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: + AgentsClient: 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) -> AgentsTransport: + """Returns the transport used by the client instance. + + Returns: + AgentsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def agent_path(project: str,) -> str: + """Returns a fully-qualified agent string.""" + return "projects/{project}/agent".format(project=project, ) + + @staticmethod + def parse_agent_path(path: str) -> Dict[str,str]: + """Parses a agent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent$", 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, AgentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the agents 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, AgentsTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, AgentsTransport): + # transport is a AgentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def get_agent(self, + request: Union[agent.GetAgentRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> agent.Agent: + r"""Retrieves the specified agent. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetAgentRequest, dict]): + The request object. The request message for + [Agents.GetAgent][google.cloud.dialogflow.v2beta1.Agents.GetAgent]. + parent (str): + Required. The project that the agent to fetch is + associated with. Format: ``projects/`` or + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Agent: + A Dialogflow agent is a virtual agent that handles conversations with your + end-users. It is a natural language understanding + module that understands the nuances of human + language. Dialogflow translates end-user text or + audio during a conversation to structured data that + your apps and services can understand. You design and + build a Dialogflow agent to handle the types of + conversations required for your system. + + For more information about agents, see the [Agent + guide](\ https://cloud.google.com/dialogflow/docs/agents-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is 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 agent.GetAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.GetAgentRequest): + request = agent.GetAgentRequest(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.get_agent] + + # Certain 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 set_agent(self, + request: Union[gcd_agent.SetAgentRequest, dict] = None, + *, + agent: gcd_agent.Agent = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_agent.Agent: + r"""Creates/updates the specified agent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.SetAgentRequest, dict]): + The request object. The request message for + [Agents.SetAgent][google.cloud.dialogflow.v2beta1.Agents.SetAgent]. + agent (google.cloud.dialogflow_v2beta1.types.Agent): + Required. The agent to update. + This corresponds to the ``agent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Agent: + A Dialogflow agent is a virtual agent that handles conversations with your + end-users. It is a natural language understanding + module that understands the nuances of human + language. Dialogflow translates end-user text or + audio during a conversation to structured data that + your apps and services can understand. You design and + build a Dialogflow agent to handle the types of + conversations required for your system. + + For more information about agents, see the [Agent + guide](\ https://cloud.google.com/dialogflow/docs/agents-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([agent]) + if request is 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 gcd_agent.SetAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_agent.SetAgentRequest): + request = gcd_agent.SetAgentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if agent is not None: + request.agent = agent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_agent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("agent.parent", request.agent.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_agent(self, + request: Union[agent.DeleteAgentRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified agent. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.DeleteAgentRequest, dict]): + The request object. The request message for + [Agents.DeleteAgent][google.cloud.dialogflow.v2beta1.Agents.DeleteAgent]. + parent (str): + Required. The project that the agent to delete is + associated with. Format: ``projects/`` or + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # 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 agent.DeleteAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.DeleteAgentRequest): + request = agent.DeleteAgentRequest(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.delete_agent] + + # Certain 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. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def search_agents(self, + request: Union[agent.SearchAgentsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAgentsPager: + r"""Returns the list of agents. Since there is at most one + conversational agent per project, this method is useful + primarily for listing all agents across projects the caller has + access to. One can achieve that with a wildcard project + collection id "-". Refer to `List + Sub-Collections `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.SearchAgentsRequest, dict]): + The request object. The request message for + [Agents.SearchAgents][google.cloud.dialogflow.v2beta1.Agents.SearchAgents]. + parent (str): + Required. The project to list agents from. Format: + ``projects/`` or + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.services.agents.pagers.SearchAgentsPager: + The response message for + [Agents.SearchAgents][google.cloud.dialogflow.v2beta1.Agents.SearchAgents]. + + 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 agent.SearchAgentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.SearchAgentsRequest): + request = agent.SearchAgentsRequest(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.search_agents] + + # Certain 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.SearchAgentsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def train_agent(self, + request: Union[agent.TrainAgentRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Trains the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.TrainAgentRequest, dict]): + The request object. The request message for + [Agents.TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent]. + parent (str): + Required. The project that the agent to train is + associated with. Format: ``projects/`` or + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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 agent.TrainAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.TrainAgentRequest): + request = agent.TrainAgentRequest(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.train_agent] + + # Certain 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, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def export_agent(self, + request: Union[agent.ExportAgentRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Exports the specified agent to a ZIP file. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ExportAgentResponse][google.cloud.dialogflow.v2beta1.ExportAgentResponse] + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ExportAgentRequest, dict]): + The request object. The request message for + [Agents.ExportAgent][google.cloud.dialogflow.v2beta1.Agents.ExportAgent]. + parent (str): + Required. The project that the agent to export is + associated with. Format: ``projects/`` or + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflow_v2beta1.types.ExportAgentResponse` + The response message for + [Agents.ExportAgent][google.cloud.dialogflow.v2beta1.Agents.ExportAgent]. + + """ + # 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 agent.ExportAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.ExportAgentRequest): + request = agent.ExportAgentRequest(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.export_agent] + + # Certain 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, + agent.ExportAgentResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def import_agent(self, + request: Union[agent.ImportAgentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Imports the specified agent from a ZIP file. + + Uploads new intents and entity types without deleting the + existing ones. Intents and entity types with the same name are + replaced with the new versions from + [ImportAgentRequest][google.cloud.dialogflow.v2beta1.ImportAgentRequest]. + After the import, the imported draft agent will be trained + automatically (unless disabled in agent settings). However, once + the import is done, training may not be completed yet. Please + call + [TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent] + and wait for the operation it returns in order to train + explicitly. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + The operation only tracks when importing is complete, not when + it is done training. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ImportAgentRequest, dict]): + The request object. The request message for + [Agents.ImportAgent][google.cloud.dialogflow.v2beta1.Agents.ImportAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a agent.ImportAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.ImportAgentRequest): + request = agent.ImportAgentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_agent] + + # Certain 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, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def restore_agent(self, + request: Union[agent.RestoreAgentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Restores the specified agent from a ZIP file. + + Replaces the current agent version with a new one. All the + intents and entity types in the older version are deleted. After + the restore, the restored draft agent will be trained + automatically (unless disabled in agent settings). However, once + the restore is done, training may not be completed yet. Please + call + [TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent] + and wait for the operation it returns in order to train + explicitly. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + The operation only tracks when restoring is complete, not when + it is done training. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.RestoreAgentRequest, dict]): + The request object. The request message for + [Agents.RestoreAgent][google.cloud.dialogflow.v2beta1.Agents.RestoreAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a agent.RestoreAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.RestoreAgentRequest): + request = agent.RestoreAgentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.restore_agent] + + # Certain 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, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def get_validation_result(self, + request: Union[agent.GetValidationResultRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> validation_result.ValidationResult: + r"""Gets agent validation result. Agent validation is + performed during training time and is updated + automatically when training is completed. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetValidationResultRequest, dict]): + The request object. The request message for + [Agents.GetValidationResult][google.cloud.dialogflow.v2beta1.Agents.GetValidationResult]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.ValidationResult: + Represents the output of agent + validation. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a agent.GetValidationResultRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.GetValidationResultRequest): + request = agent.GetValidationResultRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_validation_result] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "AgentsClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/pagers.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/pagers.py new file mode 100644 index 000000000..73a511f23 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflow_v2beta1.types import agent + + +class SearchAgentsPager: + """A pager for iterating through ``search_agents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.SearchAgentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``agents`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchAgents`` requests and continue to iterate + through the ``agents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.SearchAgentsResponse` + 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[..., agent.SearchAgentsResponse], + request: agent.SearchAgentsRequest, + response: agent.SearchAgentsResponse, + *, + 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.dialogflow_v2beta1.types.SearchAgentsRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.SearchAgentsResponse): + 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 = agent.SearchAgentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[agent.SearchAgentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[agent.Agent]: + for page in self.pages: + yield from page.agents + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchAgentsAsyncPager: + """A pager for iterating through ``search_agents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.SearchAgentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``agents`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchAgents`` requests and continue to iterate + through the ``agents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.SearchAgentsResponse` + 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[agent.SearchAgentsResponse]], + request: agent.SearchAgentsRequest, + response: agent.SearchAgentsResponse, + *, + 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.dialogflow_v2beta1.types.SearchAgentsRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.SearchAgentsResponse): + 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 = agent.SearchAgentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[agent.SearchAgentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[agent.Agent]: + async def async_generator(): + async for page in self.pages: + for response in page.agents: + 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/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/__init__.py new file mode 100644 index 000000000..0dc0c06c1 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/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 AgentsTransport +from .grpc import AgentsGrpcTransport +from .grpc_asyncio import AgentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AgentsTransport]] +_transport_registry['grpc'] = AgentsGrpcTransport +_transport_registry['grpc_asyncio'] = AgentsGrpcAsyncIOTransport + +__all__ = ( + 'AgentsTransport', + 'AgentsGrpcTransport', + 'AgentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/base.py new file mode 100644 index 000000000..8119dbab8 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.types import agent +from google.cloud.dialogflow_v2beta1.types import agent as gcd_agent +from google.cloud.dialogflow_v2beta1.types import validation_result +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-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class AgentsTransport(abc.ABC): + """Abstract transport class for Agents.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_agent: gapic_v1.method.wrap_method( + self.get_agent, + default_timeout=None, + client_info=client_info, + ), + self.set_agent: gapic_v1.method.wrap_method( + self.set_agent, + default_timeout=None, + client_info=client_info, + ), + self.delete_agent: gapic_v1.method.wrap_method( + self.delete_agent, + default_timeout=None, + client_info=client_info, + ), + self.search_agents: gapic_v1.method.wrap_method( + self.search_agents, + default_timeout=None, + client_info=client_info, + ), + self.train_agent: gapic_v1.method.wrap_method( + self.train_agent, + default_timeout=None, + client_info=client_info, + ), + self.export_agent: gapic_v1.method.wrap_method( + self.export_agent, + default_timeout=None, + client_info=client_info, + ), + self.import_agent: gapic_v1.method.wrap_method( + self.import_agent, + default_timeout=None, + client_info=client_info, + ), + self.restore_agent: gapic_v1.method.wrap_method( + self.restore_agent, + default_timeout=None, + client_info=client_info, + ), + self.get_validation_result: gapic_v1.method.wrap_method( + self.get_validation_result, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def get_agent(self) -> Callable[ + [agent.GetAgentRequest], + Union[ + agent.Agent, + Awaitable[agent.Agent] + ]]: + raise NotImplementedError() + + @property + def set_agent(self) -> Callable[ + [gcd_agent.SetAgentRequest], + Union[ + gcd_agent.Agent, + Awaitable[gcd_agent.Agent] + ]]: + raise NotImplementedError() + + @property + def delete_agent(self) -> Callable[ + [agent.DeleteAgentRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def search_agents(self) -> Callable[ + [agent.SearchAgentsRequest], + Union[ + agent.SearchAgentsResponse, + Awaitable[agent.SearchAgentsResponse] + ]]: + raise NotImplementedError() + + @property + def train_agent(self) -> Callable[ + [agent.TrainAgentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def export_agent(self) -> Callable[ + [agent.ExportAgentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def import_agent(self) -> Callable[ + [agent.ImportAgentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def restore_agent(self) -> Callable[ + [agent.RestoreAgentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_validation_result(self) -> Callable[ + [agent.GetValidationResultRequest], + Union[ + validation_result.ValidationResult, + Awaitable[validation_result.ValidationResult] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'AgentsTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc.py new file mode 100644 index 000000000..eb8046673 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc.py @@ -0,0 +1,576 @@ +# -*- 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 +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import agent +from google.cloud.dialogflow_v2beta1.types import agent as gcd_agent +from google.cloud.dialogflow_v2beta1.types import validation_result +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import AgentsTransport, DEFAULT_CLIENT_INFO + + +class AgentsGrpcTransport(AgentsTransport): + """gRPC backend transport for Agents. + + Service for managing + [Agents][google.cloud.dialogflow.v2beta1.Agent]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 = 'dialogflow.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 get_agent(self) -> Callable[ + [agent.GetAgentRequest], + agent.Agent]: + r"""Return a callable for the get agent method over gRPC. + + Retrieves the specified agent. + + Returns: + Callable[[~.GetAgentRequest], + ~.Agent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_agent' not in self._stubs: + self._stubs['get_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Agents/GetAgent', + request_serializer=agent.GetAgentRequest.serialize, + response_deserializer=agent.Agent.deserialize, + ) + return self._stubs['get_agent'] + + @property + def set_agent(self) -> Callable[ + [gcd_agent.SetAgentRequest], + gcd_agent.Agent]: + r"""Return a callable for the set agent method over gRPC. + + Creates/updates the specified agent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.SetAgentRequest], + ~.Agent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_agent' not in self._stubs: + self._stubs['set_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Agents/SetAgent', + request_serializer=gcd_agent.SetAgentRequest.serialize, + response_deserializer=gcd_agent.Agent.deserialize, + ) + return self._stubs['set_agent'] + + @property + def delete_agent(self) -> Callable[ + [agent.DeleteAgentRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete agent method over gRPC. + + Deletes the specified agent. + + Returns: + Callable[[~.DeleteAgentRequest], + ~.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_agent' not in self._stubs: + self._stubs['delete_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Agents/DeleteAgent', + request_serializer=agent.DeleteAgentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_agent'] + + @property + def search_agents(self) -> Callable[ + [agent.SearchAgentsRequest], + agent.SearchAgentsResponse]: + r"""Return a callable for the search agents method over gRPC. + + Returns the list of agents. Since there is at most one + conversational agent per project, this method is useful + primarily for listing all agents across projects the caller has + access to. One can achieve that with a wildcard project + collection id "-". Refer to `List + Sub-Collections `__. + + Returns: + Callable[[~.SearchAgentsRequest], + ~.SearchAgentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_agents' not in self._stubs: + self._stubs['search_agents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Agents/SearchAgents', + request_serializer=agent.SearchAgentsRequest.serialize, + response_deserializer=agent.SearchAgentsResponse.deserialize, + ) + return self._stubs['search_agents'] + + @property + def train_agent(self) -> Callable[ + [agent.TrainAgentRequest], + operations_pb2.Operation]: + r"""Return a callable for the train agent method over gRPC. + + Trains the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.TrainAgentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'train_agent' not in self._stubs: + self._stubs['train_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Agents/TrainAgent', + request_serializer=agent.TrainAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['train_agent'] + + @property + def export_agent(self) -> Callable[ + [agent.ExportAgentRequest], + operations_pb2.Operation]: + r"""Return a callable for the export agent method over gRPC. + + Exports the specified agent to a ZIP file. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ExportAgentResponse][google.cloud.dialogflow.v2beta1.ExportAgentResponse] + + Returns: + Callable[[~.ExportAgentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'export_agent' not in self._stubs: + self._stubs['export_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Agents/ExportAgent', + request_serializer=agent.ExportAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_agent'] + + @property + def import_agent(self) -> Callable[ + [agent.ImportAgentRequest], + operations_pb2.Operation]: + r"""Return a callable for the import agent method over gRPC. + + Imports the specified agent from a ZIP file. + + Uploads new intents and entity types without deleting the + existing ones. Intents and entity types with the same name are + replaced with the new versions from + [ImportAgentRequest][google.cloud.dialogflow.v2beta1.ImportAgentRequest]. + After the import, the imported draft agent will be trained + automatically (unless disabled in agent settings). However, once + the import is done, training may not be completed yet. Please + call + [TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent] + and wait for the operation it returns in order to train + explicitly. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + The operation only tracks when importing is complete, not when + it is done training. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.ImportAgentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_agent' not in self._stubs: + self._stubs['import_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Agents/ImportAgent', + request_serializer=agent.ImportAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_agent'] + + @property + def restore_agent(self) -> Callable[ + [agent.RestoreAgentRequest], + operations_pb2.Operation]: + r"""Return a callable for the restore agent method over gRPC. + + Restores the specified agent from a ZIP file. + + Replaces the current agent version with a new one. All the + intents and entity types in the older version are deleted. After + the restore, the restored draft agent will be trained + automatically (unless disabled in agent settings). However, once + the restore is done, training may not be completed yet. Please + call + [TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent] + and wait for the operation it returns in order to train + explicitly. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + The operation only tracks when restoring is complete, not when + it is done training. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.RestoreAgentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'restore_agent' not in self._stubs: + self._stubs['restore_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Agents/RestoreAgent', + request_serializer=agent.RestoreAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restore_agent'] + + @property + def get_validation_result(self) -> Callable[ + [agent.GetValidationResultRequest], + validation_result.ValidationResult]: + r"""Return a callable for the get validation result method over gRPC. + + Gets agent validation result. Agent validation is + performed during training time and is updated + automatically when training is completed. + + Returns: + Callable[[~.GetValidationResultRequest], + ~.ValidationResult]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_validation_result' not in self._stubs: + self._stubs['get_validation_result'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Agents/GetValidationResult', + request_serializer=agent.GetValidationResultRequest.serialize, + response_deserializer=validation_result.ValidationResult.deserialize, + ) + return self._stubs['get_validation_result'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'AgentsGrpcTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc_asyncio.py new file mode 100644 index 000000000..be965e710 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc_asyncio.py @@ -0,0 +1,580 @@ +# -*- 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 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import agent +from google.cloud.dialogflow_v2beta1.types import agent as gcd_agent +from google.cloud.dialogflow_v2beta1.types import validation_result +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import AgentsTransport, DEFAULT_CLIENT_INFO +from .grpc import AgentsGrpcTransport + + +class AgentsGrpcAsyncIOTransport(AgentsTransport): + """gRPC AsyncIO backend transport for Agents. + + Service for managing + [Agents][google.cloud.dialogflow.v2beta1.Agent]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 get_agent(self) -> Callable[ + [agent.GetAgentRequest], + Awaitable[agent.Agent]]: + r"""Return a callable for the get agent method over gRPC. + + Retrieves the specified agent. + + Returns: + Callable[[~.GetAgentRequest], + Awaitable[~.Agent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_agent' not in self._stubs: + self._stubs['get_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Agents/GetAgent', + request_serializer=agent.GetAgentRequest.serialize, + response_deserializer=agent.Agent.deserialize, + ) + return self._stubs['get_agent'] + + @property + def set_agent(self) -> Callable[ + [gcd_agent.SetAgentRequest], + Awaitable[gcd_agent.Agent]]: + r"""Return a callable for the set agent method over gRPC. + + Creates/updates the specified agent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.SetAgentRequest], + Awaitable[~.Agent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'set_agent' not in self._stubs: + self._stubs['set_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Agents/SetAgent', + request_serializer=gcd_agent.SetAgentRequest.serialize, + response_deserializer=gcd_agent.Agent.deserialize, + ) + return self._stubs['set_agent'] + + @property + def delete_agent(self) -> Callable[ + [agent.DeleteAgentRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete agent method over gRPC. + + Deletes the specified agent. + + Returns: + Callable[[~.DeleteAgentRequest], + 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_agent' not in self._stubs: + self._stubs['delete_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Agents/DeleteAgent', + request_serializer=agent.DeleteAgentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_agent'] + + @property + def search_agents(self) -> Callable[ + [agent.SearchAgentsRequest], + Awaitable[agent.SearchAgentsResponse]]: + r"""Return a callable for the search agents method over gRPC. + + Returns the list of agents. Since there is at most one + conversational agent per project, this method is useful + primarily for listing all agents across projects the caller has + access to. One can achieve that with a wildcard project + collection id "-". Refer to `List + Sub-Collections `__. + + Returns: + Callable[[~.SearchAgentsRequest], + Awaitable[~.SearchAgentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_agents' not in self._stubs: + self._stubs['search_agents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Agents/SearchAgents', + request_serializer=agent.SearchAgentsRequest.serialize, + response_deserializer=agent.SearchAgentsResponse.deserialize, + ) + return self._stubs['search_agents'] + + @property + def train_agent(self) -> Callable[ + [agent.TrainAgentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the train agent method over gRPC. + + Trains the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.TrainAgentRequest], + 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 'train_agent' not in self._stubs: + self._stubs['train_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Agents/TrainAgent', + request_serializer=agent.TrainAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['train_agent'] + + @property + def export_agent(self) -> Callable[ + [agent.ExportAgentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the export agent method over gRPC. + + Exports the specified agent to a ZIP file. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ExportAgentResponse][google.cloud.dialogflow.v2beta1.ExportAgentResponse] + + Returns: + Callable[[~.ExportAgentRequest], + 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 'export_agent' not in self._stubs: + self._stubs['export_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Agents/ExportAgent', + request_serializer=agent.ExportAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_agent'] + + @property + def import_agent(self) -> Callable[ + [agent.ImportAgentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import agent method over gRPC. + + Imports the specified agent from a ZIP file. + + Uploads new intents and entity types without deleting the + existing ones. Intents and entity types with the same name are + replaced with the new versions from + [ImportAgentRequest][google.cloud.dialogflow.v2beta1.ImportAgentRequest]. + After the import, the imported draft agent will be trained + automatically (unless disabled in agent settings). However, once + the import is done, training may not be completed yet. Please + call + [TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent] + and wait for the operation it returns in order to train + explicitly. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + The operation only tracks when importing is complete, not when + it is done training. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.ImportAgentRequest], + 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_agent' not in self._stubs: + self._stubs['import_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Agents/ImportAgent', + request_serializer=agent.ImportAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_agent'] + + @property + def restore_agent(self) -> Callable[ + [agent.RestoreAgentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the restore agent method over gRPC. + + Restores the specified agent from a ZIP file. + + Replaces the current agent version with a new one. All the + intents and entity types in the older version are deleted. After + the restore, the restored draft agent will be trained + automatically (unless disabled in agent settings). However, once + the restore is done, training may not be completed yet. Please + call + [TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent] + and wait for the operation it returns in order to train + explicitly. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + The operation only tracks when restoring is complete, not when + it is done training. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.RestoreAgentRequest], + 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 'restore_agent' not in self._stubs: + self._stubs['restore_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Agents/RestoreAgent', + request_serializer=agent.RestoreAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restore_agent'] + + @property + def get_validation_result(self) -> Callable[ + [agent.GetValidationResultRequest], + Awaitable[validation_result.ValidationResult]]: + r"""Return a callable for the get validation result method over gRPC. + + Gets agent validation result. Agent validation is + performed during training time and is updated + automatically when training is completed. + + Returns: + Callable[[~.GetValidationResultRequest], + Awaitable[~.ValidationResult]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_validation_result' not in self._stubs: + self._stubs['get_validation_result'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Agents/GetValidationResult', + request_serializer=agent.GetValidationResultRequest.serialize, + response_deserializer=validation_result.ValidationResult.deserialize, + ) + return self._stubs['get_validation_result'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'AgentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/__init__.py new file mode 100644 index 000000000..16c67859b --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/__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 AnswerRecordsClient +from .async_client import AnswerRecordsAsyncClient + +__all__ = ( + 'AnswerRecordsClient', + 'AnswerRecordsAsyncClient', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/async_client.py new file mode 100644 index 000000000..648d6738a --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/async_client.py @@ -0,0 +1,468 @@ +# -*- 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 warnings + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2beta1.services.answer_records import pagers +from google.cloud.dialogflow_v2beta1.types import answer_record +from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AnswerRecordsGrpcAsyncIOTransport +from .client import AnswerRecordsClient + + +class AnswerRecordsAsyncClient: + """Service for managing + [AnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecord]. + """ + + _client: AnswerRecordsClient + + DEFAULT_ENDPOINT = AnswerRecordsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AnswerRecordsClient.DEFAULT_MTLS_ENDPOINT + + answer_record_path = staticmethod(AnswerRecordsClient.answer_record_path) + parse_answer_record_path = staticmethod(AnswerRecordsClient.parse_answer_record_path) + common_billing_account_path = staticmethod(AnswerRecordsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AnswerRecordsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AnswerRecordsClient.common_folder_path) + parse_common_folder_path = staticmethod(AnswerRecordsClient.parse_common_folder_path) + common_organization_path = staticmethod(AnswerRecordsClient.common_organization_path) + parse_common_organization_path = staticmethod(AnswerRecordsClient.parse_common_organization_path) + common_project_path = staticmethod(AnswerRecordsClient.common_project_path) + parse_common_project_path = staticmethod(AnswerRecordsClient.parse_common_project_path) + common_location_path = staticmethod(AnswerRecordsClient.common_location_path) + parse_common_location_path = staticmethod(AnswerRecordsClient.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: + AnswerRecordsAsyncClient: The constructed client. + """ + return AnswerRecordsClient.from_service_account_info.__func__(AnswerRecordsAsyncClient, 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: + AnswerRecordsAsyncClient: The constructed client. + """ + return AnswerRecordsClient.from_service_account_file.__func__(AnswerRecordsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> AnswerRecordsTransport: + """Returns the transport used by the client instance. + + Returns: + AnswerRecordsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(AnswerRecordsClient).get_transport_class, type(AnswerRecordsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, AnswerRecordsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the answer records 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, ~.AnswerRecordsTransport]): 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 = AnswerRecordsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_answer_record(self, + request: Union[answer_record.GetAnswerRecordRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> answer_record.AnswerRecord: + r"""Deprecated. + Retrieves a specific answer record. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetAnswerRecordRequest, dict]): + The request object. Request message for + [AnswerRecords.GetAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.GetAnswerRecord]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.AnswerRecord: + Answer records are records to manage answer history and feedbacks for + Dialogflow. + + Currently, answer record includes: + + - human agent assistant article suggestion + - human agent assistant faq article + + It doesn't include: + + - DetectIntent intent matching + - DetectIntent knowledge + + Answer records are not related to the conversation + history in the Dialogflow Console. A Record is + generated even when the end-user disables + conversation history in the console. Records are + created when there's a human agent assistant + suggestion generated. + + A typical workflow for customers provide feedback to + an answer is: + + 1. For human agent assistant, customers get + suggestion via ListSuggestions API. Together with + the answers, + [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] + are returned to the customers. + 2. The customer uses the + [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] + to call the [UpdateAnswerRecord][] method to send + feedback about a specific answer that they believe + is wrong. + + """ + warnings.warn("AnswerRecordsAsyncClient.get_answer_record is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + request = answer_record.GetAnswerRecordRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_answer_record, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_answer_records(self, + request: Union[answer_record.ListAnswerRecordsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAnswerRecordsAsyncPager: + r"""Returns the list of all answer records in the + specified project in reverse chronological order. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListAnswerRecordsRequest, dict]): + The request object. Request message for + [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. + parent (:class:`str`): + Required. The project to list all answer records for in + reverse chronological order. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.services.answer_records.pagers.ListAnswerRecordsAsyncPager: + Response message for + [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. + + 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 = answer_record.ListAnswerRecordsRequest(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_answer_records, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAnswerRecordsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_answer_record(self, + request: Union[gcd_answer_record.UpdateAnswerRecordRequest, dict] = None, + *, + answer_record: gcd_answer_record.AnswerRecord = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_answer_record.AnswerRecord: + r"""Updates the specified answer record. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.UpdateAnswerRecordRequest, dict]): + The request object. Request message for + [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.UpdateAnswerRecord]. + answer_record (:class:`google.cloud.dialogflow_v2beta1.types.AnswerRecord`): + Required. Answer record to update. + This corresponds to the ``answer_record`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.AnswerRecord: + Answer records are records to manage answer history and feedbacks for + Dialogflow. + + Currently, answer record includes: + + - human agent assistant article suggestion + - human agent assistant faq article + + It doesn't include: + + - DetectIntent intent matching + - DetectIntent knowledge + + Answer records are not related to the conversation + history in the Dialogflow Console. A Record is + generated even when the end-user disables + conversation history in the console. Records are + created when there's a human agent assistant + suggestion generated. + + A typical workflow for customers provide feedback to + an answer is: + + 1. For human agent assistant, customers get + suggestion via ListSuggestions API. Together with + the answers, + [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] + are returned to the customers. + 2. The customer uses the + [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] + to call the [UpdateAnswerRecord][] method to send + feedback about a specific answer that they believe + is wrong. + + """ + # 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([answer_record, 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 = gcd_answer_record.UpdateAnswerRecordRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if answer_record is not None: + request.answer_record = answer_record + 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_answer_record, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("answer_record.name", request.answer_record.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "AnswerRecordsAsyncClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/client.py new file mode 100644 index 000000000..8b792cc80 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/client.py @@ -0,0 +1,667 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2beta1.services.answer_records import pagers +from google.cloud.dialogflow_v2beta1.types import answer_record +from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AnswerRecordsGrpcTransport +from .transports.grpc_asyncio import AnswerRecordsGrpcAsyncIOTransport + + +class AnswerRecordsClientMeta(type): + """Metaclass for the AnswerRecords 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[AnswerRecordsTransport]] + _transport_registry["grpc"] = AnswerRecordsGrpcTransport + _transport_registry["grpc_asyncio"] = AnswerRecordsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[AnswerRecordsTransport]: + """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 AnswerRecordsClient(metaclass=AnswerRecordsClientMeta): + """Service for managing + [AnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecord]. + """ + + @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 = "dialogflow.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: + AnswerRecordsClient: 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: + AnswerRecordsClient: 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) -> AnswerRecordsTransport: + """Returns the transport used by the client instance. + + Returns: + AnswerRecordsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def answer_record_path(project: str,answer_record: str,) -> str: + """Returns a fully-qualified answer_record string.""" + return "projects/{project}/answerRecords/{answer_record}".format(project=project, answer_record=answer_record, ) + + @staticmethod + def parse_answer_record_path(path: str) -> Dict[str,str]: + """Parses a answer_record path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/answerRecords/(?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, AnswerRecordsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the answer records 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, AnswerRecordsTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, AnswerRecordsTransport): + # transport is a AnswerRecordsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def get_answer_record(self, + request: Union[answer_record.GetAnswerRecordRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> answer_record.AnswerRecord: + r"""Deprecated. + Retrieves a specific answer record. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetAnswerRecordRequest, dict]): + The request object. Request message for + [AnswerRecords.GetAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.GetAnswerRecord]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.AnswerRecord: + Answer records are records to manage answer history and feedbacks for + Dialogflow. + + Currently, answer record includes: + + - human agent assistant article suggestion + - human agent assistant faq article + + It doesn't include: + + - DetectIntent intent matching + - DetectIntent knowledge + + Answer records are not related to the conversation + history in the Dialogflow Console. A Record is + generated even when the end-user disables + conversation history in the console. Records are + created when there's a human agent assistant + suggestion generated. + + A typical workflow for customers provide feedback to + an answer is: + + 1. For human agent assistant, customers get + suggestion via ListSuggestions API. Together with + the answers, + [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] + are returned to the customers. + 2. The customer uses the + [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] + to call the [UpdateAnswerRecord][] method to send + feedback about a specific answer that they believe + is wrong. + + """ + warnings.warn("AnswerRecordsClient.get_answer_record is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a answer_record.GetAnswerRecordRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, answer_record.GetAnswerRecordRequest): + request = answer_record.GetAnswerRecordRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_answer_record] + + # Certain 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_answer_records(self, + request: Union[answer_record.ListAnswerRecordsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAnswerRecordsPager: + r"""Returns the list of all answer records in the + specified project in reverse chronological order. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListAnswerRecordsRequest, dict]): + The request object. Request message for + [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. + parent (str): + Required. The project to list all answer records for in + reverse chronological order. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.services.answer_records.pagers.ListAnswerRecordsPager: + Response message for + [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. + + 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 answer_record.ListAnswerRecordsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, answer_record.ListAnswerRecordsRequest): + request = answer_record.ListAnswerRecordsRequest(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_answer_records] + + # Certain 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.ListAnswerRecordsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_answer_record(self, + request: Union[gcd_answer_record.UpdateAnswerRecordRequest, dict] = None, + *, + answer_record: gcd_answer_record.AnswerRecord = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_answer_record.AnswerRecord: + r"""Updates the specified answer record. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.UpdateAnswerRecordRequest, dict]): + The request object. Request message for + [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.UpdateAnswerRecord]. + answer_record (google.cloud.dialogflow_v2beta1.types.AnswerRecord): + Required. Answer record to update. + This corresponds to the ``answer_record`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.AnswerRecord: + Answer records are records to manage answer history and feedbacks for + Dialogflow. + + Currently, answer record includes: + + - human agent assistant article suggestion + - human agent assistant faq article + + It doesn't include: + + - DetectIntent intent matching + - DetectIntent knowledge + + Answer records are not related to the conversation + history in the Dialogflow Console. A Record is + generated even when the end-user disables + conversation history in the console. Records are + created when there's a human agent assistant + suggestion generated. + + A typical workflow for customers provide feedback to + an answer is: + + 1. For human agent assistant, customers get + suggestion via ListSuggestions API. Together with + the answers, + [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] + are returned to the customers. + 2. The customer uses the + [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] + to call the [UpdateAnswerRecord][] method to send + feedback about a specific answer that they believe + is wrong. + + """ + # 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([answer_record, 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 gcd_answer_record.UpdateAnswerRecordRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_answer_record.UpdateAnswerRecordRequest): + request = gcd_answer_record.UpdateAnswerRecordRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if answer_record is not None: + request.answer_record = answer_record + 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_answer_record] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("answer_record.name", request.answer_record.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "AnswerRecordsClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/pagers.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/pagers.py new file mode 100644 index 000000000..7de91b91a --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflow_v2beta1.types import answer_record + + +class ListAnswerRecordsPager: + """A pager for iterating through ``list_answer_records`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListAnswerRecordsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``answer_records`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAnswerRecords`` requests and continue to iterate + through the ``answer_records`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListAnswerRecordsResponse` + 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[..., answer_record.ListAnswerRecordsResponse], + request: answer_record.ListAnswerRecordsRequest, + response: answer_record.ListAnswerRecordsResponse, + *, + 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.dialogflow_v2beta1.types.ListAnswerRecordsRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListAnswerRecordsResponse): + 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 = answer_record.ListAnswerRecordsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[answer_record.ListAnswerRecordsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[answer_record.AnswerRecord]: + for page in self.pages: + yield from page.answer_records + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAnswerRecordsAsyncPager: + """A pager for iterating through ``list_answer_records`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListAnswerRecordsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``answer_records`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAnswerRecords`` requests and continue to iterate + through the ``answer_records`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListAnswerRecordsResponse` + 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[answer_record.ListAnswerRecordsResponse]], + request: answer_record.ListAnswerRecordsRequest, + response: answer_record.ListAnswerRecordsResponse, + *, + 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.dialogflow_v2beta1.types.ListAnswerRecordsRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListAnswerRecordsResponse): + 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 = answer_record.ListAnswerRecordsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[answer_record.ListAnswerRecordsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[answer_record.AnswerRecord]: + async def async_generator(): + async for page in self.pages: + for response in page.answer_records: + 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/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/__init__.py new file mode 100644 index 000000000..99c08cf37 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/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 AnswerRecordsTransport +from .grpc import AnswerRecordsGrpcTransport +from .grpc_asyncio import AnswerRecordsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AnswerRecordsTransport]] +_transport_registry['grpc'] = AnswerRecordsGrpcTransport +_transport_registry['grpc_asyncio'] = AnswerRecordsGrpcAsyncIOTransport + +__all__ = ( + 'AnswerRecordsTransport', + 'AnswerRecordsGrpcTransport', + 'AnswerRecordsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/base.py new file mode 100644 index 000000000..064f25173 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/base.py @@ -0,0 +1,176 @@ +# -*- 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.types import answer_record +from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class AnswerRecordsTransport(abc.ABC): + """Abstract transport class for AnswerRecords.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_answer_record: gapic_v1.method.wrap_method( + self.get_answer_record, + default_timeout=None, + client_info=client_info, + ), + self.list_answer_records: gapic_v1.method.wrap_method( + self.list_answer_records, + default_timeout=None, + client_info=client_info, + ), + self.update_answer_record: gapic_v1.method.wrap_method( + self.update_answer_record, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def get_answer_record(self) -> Callable[ + [answer_record.GetAnswerRecordRequest], + Union[ + answer_record.AnswerRecord, + Awaitable[answer_record.AnswerRecord] + ]]: + raise NotImplementedError() + + @property + def list_answer_records(self) -> Callable[ + [answer_record.ListAnswerRecordsRequest], + Union[ + answer_record.ListAnswerRecordsResponse, + Awaitable[answer_record.ListAnswerRecordsResponse] + ]]: + raise NotImplementedError() + + @property + def update_answer_record(self) -> Callable[ + [gcd_answer_record.UpdateAnswerRecordRequest], + Union[ + gcd_answer_record.AnswerRecord, + Awaitable[gcd_answer_record.AnswerRecord] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'AnswerRecordsTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc.py new file mode 100644 index 000000000..b0cf6328a --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc.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. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import answer_record +from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record +from .base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO + + +class AnswerRecordsGrpcTransport(AnswerRecordsTransport): + """gRPC backend transport for AnswerRecords. + + Service for managing + [AnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecord]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def get_answer_record(self) -> Callable[ + [answer_record.GetAnswerRecordRequest], + answer_record.AnswerRecord]: + r"""Return a callable for the get answer record method over gRPC. + + Deprecated. + Retrieves a specific answer record. + + Returns: + Callable[[~.GetAnswerRecordRequest], + ~.AnswerRecord]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_answer_record' not in self._stubs: + self._stubs['get_answer_record'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.AnswerRecords/GetAnswerRecord', + request_serializer=answer_record.GetAnswerRecordRequest.serialize, + response_deserializer=answer_record.AnswerRecord.deserialize, + ) + return self._stubs['get_answer_record'] + + @property + def list_answer_records(self) -> Callable[ + [answer_record.ListAnswerRecordsRequest], + answer_record.ListAnswerRecordsResponse]: + r"""Return a callable for the list answer records method over gRPC. + + Returns the list of all answer records in the + specified project in reverse chronological order. + + Returns: + Callable[[~.ListAnswerRecordsRequest], + ~.ListAnswerRecordsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_answer_records' not in self._stubs: + self._stubs['list_answer_records'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.AnswerRecords/ListAnswerRecords', + request_serializer=answer_record.ListAnswerRecordsRequest.serialize, + response_deserializer=answer_record.ListAnswerRecordsResponse.deserialize, + ) + return self._stubs['list_answer_records'] + + @property + def update_answer_record(self) -> Callable[ + [gcd_answer_record.UpdateAnswerRecordRequest], + gcd_answer_record.AnswerRecord]: + r"""Return a callable for the update answer record method over gRPC. + + Updates the specified answer record. + + Returns: + Callable[[~.UpdateAnswerRecordRequest], + ~.AnswerRecord]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_answer_record' not in self._stubs: + self._stubs['update_answer_record'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.AnswerRecords/UpdateAnswerRecord', + request_serializer=gcd_answer_record.UpdateAnswerRecordRequest.serialize, + response_deserializer=gcd_answer_record.AnswerRecord.deserialize, + ) + return self._stubs['update_answer_record'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'AnswerRecordsGrpcTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc_asyncio.py new file mode 100644 index 000000000..c4634dc73 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc_asyncio.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 Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import answer_record +from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record +from .base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO +from .grpc import AnswerRecordsGrpcTransport + + +class AnswerRecordsGrpcAsyncIOTransport(AnswerRecordsTransport): + """gRPC AsyncIO backend transport for AnswerRecords. + + Service for managing + [AnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecord]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def get_answer_record(self) -> Callable[ + [answer_record.GetAnswerRecordRequest], + Awaitable[answer_record.AnswerRecord]]: + r"""Return a callable for the get answer record method over gRPC. + + Deprecated. + Retrieves a specific answer record. + + Returns: + Callable[[~.GetAnswerRecordRequest], + Awaitable[~.AnswerRecord]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_answer_record' not in self._stubs: + self._stubs['get_answer_record'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.AnswerRecords/GetAnswerRecord', + request_serializer=answer_record.GetAnswerRecordRequest.serialize, + response_deserializer=answer_record.AnswerRecord.deserialize, + ) + return self._stubs['get_answer_record'] + + @property + def list_answer_records(self) -> Callable[ + [answer_record.ListAnswerRecordsRequest], + Awaitable[answer_record.ListAnswerRecordsResponse]]: + r"""Return a callable for the list answer records method over gRPC. + + Returns the list of all answer records in the + specified project in reverse chronological order. + + Returns: + Callable[[~.ListAnswerRecordsRequest], + Awaitable[~.ListAnswerRecordsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_answer_records' not in self._stubs: + self._stubs['list_answer_records'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.AnswerRecords/ListAnswerRecords', + request_serializer=answer_record.ListAnswerRecordsRequest.serialize, + response_deserializer=answer_record.ListAnswerRecordsResponse.deserialize, + ) + return self._stubs['list_answer_records'] + + @property + def update_answer_record(self) -> Callable[ + [gcd_answer_record.UpdateAnswerRecordRequest], + Awaitable[gcd_answer_record.AnswerRecord]]: + r"""Return a callable for the update answer record method over gRPC. + + Updates the specified answer record. + + Returns: + Callable[[~.UpdateAnswerRecordRequest], + Awaitable[~.AnswerRecord]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_answer_record' not in self._stubs: + self._stubs['update_answer_record'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.AnswerRecords/UpdateAnswerRecord', + request_serializer=gcd_answer_record.UpdateAnswerRecordRequest.serialize, + response_deserializer=gcd_answer_record.AnswerRecord.deserialize, + ) + return self._stubs['update_answer_record'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'AnswerRecordsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/__init__.py new file mode 100644 index 000000000..b0d60f297 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/__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 ContextsClient +from .async_client import ContextsAsyncClient + +__all__ = ( + 'ContextsClient', + 'ContextsAsyncClient', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/async_client.py new file mode 100644 index 000000000..2c8b9a57b --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/async_client.py @@ -0,0 +1,738 @@ +# -*- 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 + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2beta1.services.contexts import pagers +from google.cloud.dialogflow_v2beta1.types import context +from google.cloud.dialogflow_v2beta1.types import context as gcd_context +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import ContextsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ContextsGrpcAsyncIOTransport +from .client import ContextsClient + + +class ContextsAsyncClient: + """Service for managing + [Contexts][google.cloud.dialogflow.v2beta1.Context]. + """ + + _client: ContextsClient + + DEFAULT_ENDPOINT = ContextsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ContextsClient.DEFAULT_MTLS_ENDPOINT + + context_path = staticmethod(ContextsClient.context_path) + parse_context_path = staticmethod(ContextsClient.parse_context_path) + common_billing_account_path = staticmethod(ContextsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ContextsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ContextsClient.common_folder_path) + parse_common_folder_path = staticmethod(ContextsClient.parse_common_folder_path) + common_organization_path = staticmethod(ContextsClient.common_organization_path) + parse_common_organization_path = staticmethod(ContextsClient.parse_common_organization_path) + common_project_path = staticmethod(ContextsClient.common_project_path) + parse_common_project_path = staticmethod(ContextsClient.parse_common_project_path) + common_location_path = staticmethod(ContextsClient.common_location_path) + parse_common_location_path = staticmethod(ContextsClient.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: + ContextsAsyncClient: The constructed client. + """ + return ContextsClient.from_service_account_info.__func__(ContextsAsyncClient, 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: + ContextsAsyncClient: The constructed client. + """ + return ContextsClient.from_service_account_file.__func__(ContextsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ContextsTransport: + """Returns the transport used by the client instance. + + Returns: + ContextsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ContextsClient).get_transport_class, type(ContextsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ContextsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the contexts 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, ~.ContextsTransport]): 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 = ContextsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_contexts(self, + request: Union[context.ListContextsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListContextsAsyncPager: + r"""Returns the list of all contexts in the specified + session. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListContextsRequest, dict]): + The request object. The request message for + [Contexts.ListContexts][google.cloud.dialogflow.v2beta1.Contexts.ListContexts]. + parent (:class:`str`): + Required. The session to list all contexts from. + Supported formats: + + - \`projects//agent/sessions/, + - ``projects//locations//agent/sessions/``, + - ``projects//agent/environments//users//sessions/``, + - ``projects//locations//agent/environments//users//sessions/``, + + If ``Location ID`` is not specified we assume default + 'us' location. If ``Environment ID`` is not specified, + we assume default 'draft' environment. If ``User ID`` is + not specified, we assume default '-' user. + + 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.dialogflow_v2beta1.services.contexts.pagers.ListContextsAsyncPager: + The response message for + [Contexts.ListContexts][google.cloud.dialogflow.v2beta1.Contexts.ListContexts]. + + 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 = context.ListContextsRequest(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_contexts, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListContextsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_context(self, + request: Union[context.GetContextRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> context.Context: + r"""Retrieves the specified context. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetContextRequest, dict]): + The request object. The request message for + [Contexts.GetContext][google.cloud.dialogflow.v2beta1.Contexts.GetContext]. + name (:class:`str`): + Required. The name of the context. Supported formats: + + - ``projects//agent/sessions//contexts/``, + - ``projects//locations//agent/sessions//contexts/``, + - ``projects//agent/environments//users//sessions//contexts/``, + - ``projects//locations//agent/environments//users//sessions//contexts/``, + + If ``Location ID`` is not specified we assume default + 'us' location. If ``Environment ID`` is not specified, + we assume default 'draft' environment. If ``User ID`` is + not specified, we assume default '-' user. + + 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.dialogflow_v2beta1.types.Context: + Dialogflow contexts are similar to natural language context. If a person says + to you "they are orange", you need context in order + to understand what "they" is referring to. Similarly, + for Dialogflow to handle an end-user expression like + that, it needs to be provided with context in order + to correctly match an intent. + + Using contexts, you can control the flow of a + conversation. You can configure contexts for an + intent by setting input and output contexts, which + are identified by string names. When an intent is + matched, any configured output contexts for that + intent become active. While any contexts are active, + Dialogflow is more likely to match intents that are + configured with input contexts that correspond to the + currently active contexts. + + For more information about context, see the [Contexts + guide](\ https://cloud.google.com/dialogflow/docs/contexts-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = context.GetContextRequest(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_context, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_context(self, + request: Union[gcd_context.CreateContextRequest, dict] = None, + *, + parent: str = None, + context: gcd_context.Context = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_context.Context: + r"""Creates a context. + If the specified context already exists, overrides the + context. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.CreateContextRequest, dict]): + The request object. The request message for + [Contexts.CreateContext][google.cloud.dialogflow.v2beta1.Contexts.CreateContext]. + parent (:class:`str`): + Required. The session to create a context for. Supported + formats: + + - \`projects//agent/sessions/, + - ``projects//locations//agent/sessions/``, + - ``projects//agent/environments//users//sessions/``, + - ``projects//locations//agent/environments//users//sessions/``, + + If ``Location ID`` is not specified we assume default + 'us' location. If ``Environment ID`` is not specified, + we assume default 'draft' environment. If ``User ID`` is + not specified, we assume default '-' user. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + context (:class:`google.cloud.dialogflow_v2beta1.types.Context`): + Required. The context to create. + This corresponds to the ``context`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Context: + Dialogflow contexts are similar to natural language context. If a person says + to you "they are orange", you need context in order + to understand what "they" is referring to. Similarly, + for Dialogflow to handle an end-user expression like + that, it needs to be provided with context in order + to correctly match an intent. + + Using contexts, you can control the flow of a + conversation. You can configure contexts for an + intent by setting input and output contexts, which + are identified by string names. When an intent is + matched, any configured output contexts for that + intent become active. While any contexts are active, + Dialogflow is more likely to match intents that are + configured with input contexts that correspond to the + currently active contexts. + + For more information about context, see the [Contexts + guide](\ https://cloud.google.com/dialogflow/docs/contexts-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, context]) + if request is 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 = gcd_context.CreateContextRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if context is not None: + request.context = context + + # 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_context, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_context(self, + request: Union[gcd_context.UpdateContextRequest, dict] = None, + *, + context: gcd_context.Context = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_context.Context: + r"""Updates the specified context. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.UpdateContextRequest, dict]): + The request object. The request message for + [Contexts.UpdateContext][google.cloud.dialogflow.v2beta1.Contexts.UpdateContext]. + context (:class:`google.cloud.dialogflow_v2beta1.types.Context`): + Required. The context to update. + This corresponds to the ``context`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Context: + Dialogflow contexts are similar to natural language context. If a person says + to you "they are orange", you need context in order + to understand what "they" is referring to. Similarly, + for Dialogflow to handle an end-user expression like + that, it needs to be provided with context in order + to correctly match an intent. + + Using contexts, you can control the flow of a + conversation. You can configure contexts for an + intent by setting input and output contexts, which + are identified by string names. When an intent is + matched, any configured output contexts for that + intent become active. While any contexts are active, + Dialogflow is more likely to match intents that are + configured with input contexts that correspond to the + currently active contexts. + + For more information about context, see the [Contexts + guide](\ https://cloud.google.com/dialogflow/docs/contexts-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([context, 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 = gcd_context.UpdateContextRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if context is not None: + request.context = context + 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_context, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("context.name", request.context.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_context(self, + request: Union[context.DeleteContextRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified context. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.DeleteContextRequest, dict]): + The request object. The request message for + [Contexts.DeleteContext][google.cloud.dialogflow.v2beta1.Contexts.DeleteContext]. + name (:class:`str`): + Required. The name of the context to delete. Supported + formats: + + - ``projects//agent/sessions//contexts/``, + - ``projects//locations//agent/sessions//contexts/``, + - ``projects//agent/environments//users//sessions//contexts/``, + - ``projects//locations//agent/environments//users//sessions//contexts/``, + + If ``Location ID`` is not specified we assume default + 'us' location. If ``Environment ID`` is not specified, + we assume default 'draft' environment. If ``User ID`` is + not specified, we assume default '-' user. + + 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 = context.DeleteContextRequest(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_context, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def delete_all_contexts(self, + request: Union[context.DeleteAllContextsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes all active contexts in the specified session. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.DeleteAllContextsRequest, dict]): + The request object. The request message for + [Contexts.DeleteAllContexts][google.cloud.dialogflow.v2beta1.Contexts.DeleteAllContexts]. + parent (:class:`str`): + Required. The name of the session to delete all contexts + from. Supported formats: + + - \`projects//agent/sessions/, + - ``projects//locations//agent/sessions/``, + - ``projects//agent/environments//users//sessions/``, + - ``projects//locations//agent/environments//users//sessions/``, + + If ``Location ID`` is not specified we assume default + 'us' location. If ``Environment ID`` is not specified we + assume default 'draft' environment. If ``User ID`` is + not specified, we assume default '-' user. + + 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. + """ + # 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 = context.DeleteAllContextsRequest(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.delete_all_contexts, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ContextsAsyncClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/client.py new file mode 100644 index 000000000..3b1b224ba --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/client.py @@ -0,0 +1,936 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2beta1.services.contexts import pagers +from google.cloud.dialogflow_v2beta1.types import context +from google.cloud.dialogflow_v2beta1.types import context as gcd_context +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import ContextsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ContextsGrpcTransport +from .transports.grpc_asyncio import ContextsGrpcAsyncIOTransport + + +class ContextsClientMeta(type): + """Metaclass for the Contexts 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[ContextsTransport]] + _transport_registry["grpc"] = ContextsGrpcTransport + _transport_registry["grpc_asyncio"] = ContextsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ContextsTransport]: + """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 ContextsClient(metaclass=ContextsClientMeta): + """Service for managing + [Contexts][google.cloud.dialogflow.v2beta1.Context]. + """ + + @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 = "dialogflow.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: + ContextsClient: 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: + ContextsClient: 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) -> ContextsTransport: + """Returns the transport used by the client instance. + + Returns: + ContextsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def context_path(project: str,session: str,context: str,) -> str: + """Returns a fully-qualified context string.""" + return "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) + + @staticmethod + def parse_context_path(path: str) -> Dict[str,str]: + """Parses a context path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/contexts/(?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, ContextsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the contexts 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, ContextsTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, ContextsTransport): + # transport is a ContextsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_contexts(self, + request: Union[context.ListContextsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListContextsPager: + r"""Returns the list of all contexts in the specified + session. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListContextsRequest, dict]): + The request object. The request message for + [Contexts.ListContexts][google.cloud.dialogflow.v2beta1.Contexts.ListContexts]. + parent (str): + Required. The session to list all contexts from. + Supported formats: + + - \`projects//agent/sessions/, + - ``projects//locations//agent/sessions/``, + - ``projects//agent/environments//users//sessions/``, + - ``projects//locations//agent/environments//users//sessions/``, + + If ``Location ID`` is not specified we assume default + 'us' location. If ``Environment ID`` is not specified, + we assume default 'draft' environment. If ``User ID`` is + not specified, we assume default '-' user. + + 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.dialogflow_v2beta1.services.contexts.pagers.ListContextsPager: + The response message for + [Contexts.ListContexts][google.cloud.dialogflow.v2beta1.Contexts.ListContexts]. + + 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 context.ListContextsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, context.ListContextsRequest): + request = context.ListContextsRequest(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_contexts] + + # Certain 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.ListContextsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_context(self, + request: Union[context.GetContextRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> context.Context: + r"""Retrieves the specified context. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetContextRequest, dict]): + The request object. The request message for + [Contexts.GetContext][google.cloud.dialogflow.v2beta1.Contexts.GetContext]. + name (str): + Required. The name of the context. Supported formats: + + - ``projects//agent/sessions//contexts/``, + - ``projects//locations//agent/sessions//contexts/``, + - ``projects//agent/environments//users//sessions//contexts/``, + - ``projects//locations//agent/environments//users//sessions//contexts/``, + + If ``Location ID`` is not specified we assume default + 'us' location. If ``Environment ID`` is not specified, + we assume default 'draft' environment. If ``User ID`` is + not specified, we assume default '-' user. + + 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.dialogflow_v2beta1.types.Context: + Dialogflow contexts are similar to natural language context. If a person says + to you "they are orange", you need context in order + to understand what "they" is referring to. Similarly, + for Dialogflow to handle an end-user expression like + that, it needs to be provided with context in order + to correctly match an intent. + + Using contexts, you can control the flow of a + conversation. You can configure contexts for an + intent by setting input and output contexts, which + are identified by string names. When an intent is + matched, any configured output contexts for that + intent become active. While any contexts are active, + Dialogflow is more likely to match intents that are + configured with input contexts that correspond to the + currently active contexts. + + For more information about context, see the [Contexts + guide](\ https://cloud.google.com/dialogflow/docs/contexts-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a context.GetContextRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, context.GetContextRequest): + request = context.GetContextRequest(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_context] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_context(self, + request: Union[gcd_context.CreateContextRequest, dict] = None, + *, + parent: str = None, + context: gcd_context.Context = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_context.Context: + r"""Creates a context. + If the specified context already exists, overrides the + context. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.CreateContextRequest, dict]): + The request object. The request message for + [Contexts.CreateContext][google.cloud.dialogflow.v2beta1.Contexts.CreateContext]. + parent (str): + Required. The session to create a context for. Supported + formats: + + - \`projects//agent/sessions/, + - ``projects//locations//agent/sessions/``, + - ``projects//agent/environments//users//sessions/``, + - ``projects//locations//agent/environments//users//sessions/``, + + If ``Location ID`` is not specified we assume default + 'us' location. If ``Environment ID`` is not specified, + we assume default 'draft' environment. If ``User ID`` is + not specified, we assume default '-' user. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + context (google.cloud.dialogflow_v2beta1.types.Context): + Required. The context to create. + This corresponds to the ``context`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Context: + Dialogflow contexts are similar to natural language context. If a person says + to you "they are orange", you need context in order + to understand what "they" is referring to. Similarly, + for Dialogflow to handle an end-user expression like + that, it needs to be provided with context in order + to correctly match an intent. + + Using contexts, you can control the flow of a + conversation. You can configure contexts for an + intent by setting input and output contexts, which + are identified by string names. When an intent is + matched, any configured output contexts for that + intent become active. While any contexts are active, + Dialogflow is more likely to match intents that are + configured with input contexts that correspond to the + currently active contexts. + + For more information about context, see the [Contexts + guide](\ https://cloud.google.com/dialogflow/docs/contexts-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, context]) + if request is 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 gcd_context.CreateContextRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_context.CreateContextRequest): + request = gcd_context.CreateContextRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if context is not None: + request.context = context + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_context] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_context(self, + request: Union[gcd_context.UpdateContextRequest, dict] = None, + *, + context: gcd_context.Context = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_context.Context: + r"""Updates the specified context. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.UpdateContextRequest, dict]): + The request object. The request message for + [Contexts.UpdateContext][google.cloud.dialogflow.v2beta1.Contexts.UpdateContext]. + context (google.cloud.dialogflow_v2beta1.types.Context): + Required. The context to update. + This corresponds to the ``context`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Context: + Dialogflow contexts are similar to natural language context. If a person says + to you "they are orange", you need context in order + to understand what "they" is referring to. Similarly, + for Dialogflow to handle an end-user expression like + that, it needs to be provided with context in order + to correctly match an intent. + + Using contexts, you can control the flow of a + conversation. You can configure contexts for an + intent by setting input and output contexts, which + are identified by string names. When an intent is + matched, any configured output contexts for that + intent become active. While any contexts are active, + Dialogflow is more likely to match intents that are + configured with input contexts that correspond to the + currently active contexts. + + For more information about context, see the [Contexts + guide](\ https://cloud.google.com/dialogflow/docs/contexts-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([context, 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 gcd_context.UpdateContextRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_context.UpdateContextRequest): + request = gcd_context.UpdateContextRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if context is not None: + request.context = context + 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_context] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("context.name", request.context.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_context(self, + request: Union[context.DeleteContextRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified context. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.DeleteContextRequest, dict]): + The request object. The request message for + [Contexts.DeleteContext][google.cloud.dialogflow.v2beta1.Contexts.DeleteContext]. + name (str): + Required. The name of the context to delete. Supported + formats: + + - ``projects//agent/sessions//contexts/``, + - ``projects//locations//agent/sessions//contexts/``, + - ``projects//agent/environments//users//sessions//contexts/``, + - ``projects//locations//agent/environments//users//sessions//contexts/``, + + If ``Location ID`` is not specified we assume default + 'us' location. If ``Environment ID`` is not specified, + we assume default 'draft' environment. If ``User ID`` is + not specified, we assume default '-' user. + + 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 context.DeleteContextRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, context.DeleteContextRequest): + request = context.DeleteContextRequest(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_context] + + # Certain 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 delete_all_contexts(self, + request: Union[context.DeleteAllContextsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes all active contexts in the specified session. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.DeleteAllContextsRequest, dict]): + The request object. The request message for + [Contexts.DeleteAllContexts][google.cloud.dialogflow.v2beta1.Contexts.DeleteAllContexts]. + parent (str): + Required. The name of the session to delete all contexts + from. Supported formats: + + - \`projects//agent/sessions/, + - ``projects//locations//agent/sessions/``, + - ``projects//agent/environments//users//sessions/``, + - ``projects//locations//agent/environments//users//sessions/``, + + If ``Location ID`` is not specified we assume default + 'us' location. If ``Environment ID`` is not specified we + assume default 'draft' environment. If ``User ID`` is + not specified, we assume default '-' user. + + 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. + """ + # 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 context.DeleteAllContextsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, context.DeleteAllContextsRequest): + request = context.DeleteAllContextsRequest(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.delete_all_contexts] + + # Certain 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. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ContextsClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/pagers.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/pagers.py new file mode 100644 index 000000000..1e2cbe83c --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflow_v2beta1.types import context + + +class ListContextsPager: + """A pager for iterating through ``list_contexts`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListContextsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``contexts`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListContexts`` requests and continue to iterate + through the ``contexts`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListContextsResponse` + 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[..., context.ListContextsResponse], + request: context.ListContextsRequest, + response: context.ListContextsResponse, + *, + 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.dialogflow_v2beta1.types.ListContextsRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListContextsResponse): + 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 = context.ListContextsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[context.ListContextsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[context.Context]: + for page in self.pages: + yield from page.contexts + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListContextsAsyncPager: + """A pager for iterating through ``list_contexts`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListContextsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``contexts`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListContexts`` requests and continue to iterate + through the ``contexts`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListContextsResponse` + 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[context.ListContextsResponse]], + request: context.ListContextsRequest, + response: context.ListContextsResponse, + *, + 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.dialogflow_v2beta1.types.ListContextsRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListContextsResponse): + 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 = context.ListContextsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[context.ListContextsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[context.Context]: + async def async_generator(): + async for page in self.pages: + for response in page.contexts: + 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/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/__init__.py new file mode 100644 index 000000000..eb854f545 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/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 ContextsTransport +from .grpc import ContextsGrpcTransport +from .grpc_asyncio import ContextsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ContextsTransport]] +_transport_registry['grpc'] = ContextsGrpcTransport +_transport_registry['grpc_asyncio'] = ContextsGrpcAsyncIOTransport + +__all__ = ( + 'ContextsTransport', + 'ContextsGrpcTransport', + 'ContextsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/base.py new file mode 100644 index 000000000..76ea10684 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/base.py @@ -0,0 +1,219 @@ +# -*- 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.types import context +from google.cloud.dialogflow_v2beta1.types import context as gcd_context +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-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ContextsTransport(abc.ABC): + """Abstract transport class for Contexts.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_contexts: gapic_v1.method.wrap_method( + self.list_contexts, + default_timeout=None, + client_info=client_info, + ), + self.get_context: gapic_v1.method.wrap_method( + self.get_context, + default_timeout=None, + client_info=client_info, + ), + self.create_context: gapic_v1.method.wrap_method( + self.create_context, + default_timeout=None, + client_info=client_info, + ), + self.update_context: gapic_v1.method.wrap_method( + self.update_context, + default_timeout=None, + client_info=client_info, + ), + self.delete_context: gapic_v1.method.wrap_method( + self.delete_context, + default_timeout=None, + client_info=client_info, + ), + self.delete_all_contexts: gapic_v1.method.wrap_method( + self.delete_all_contexts, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_contexts(self) -> Callable[ + [context.ListContextsRequest], + Union[ + context.ListContextsResponse, + Awaitable[context.ListContextsResponse] + ]]: + raise NotImplementedError() + + @property + def get_context(self) -> Callable[ + [context.GetContextRequest], + Union[ + context.Context, + Awaitable[context.Context] + ]]: + raise NotImplementedError() + + @property + def create_context(self) -> Callable[ + [gcd_context.CreateContextRequest], + Union[ + gcd_context.Context, + Awaitable[gcd_context.Context] + ]]: + raise NotImplementedError() + + @property + def update_context(self) -> Callable[ + [gcd_context.UpdateContextRequest], + Union[ + gcd_context.Context, + Awaitable[gcd_context.Context] + ]]: + raise NotImplementedError() + + @property + def delete_context(self) -> Callable[ + [context.DeleteContextRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def delete_all_contexts(self) -> Callable[ + [context.DeleteAllContextsRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'ContextsTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc.py new file mode 100644 index 000000000..faf721564 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc.py @@ -0,0 +1,390 @@ +# -*- 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 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import context +from google.cloud.dialogflow_v2beta1.types import context as gcd_context +from google.protobuf import empty_pb2 # type: ignore +from .base import ContextsTransport, DEFAULT_CLIENT_INFO + + +class ContextsGrpcTransport(ContextsTransport): + """gRPC backend transport for Contexts. + + Service for managing + [Contexts][google.cloud.dialogflow.v2beta1.Context]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 = 'dialogflow.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 list_contexts(self) -> Callable[ + [context.ListContextsRequest], + context.ListContextsResponse]: + r"""Return a callable for the list contexts method over gRPC. + + Returns the list of all contexts in the specified + session. + + Returns: + Callable[[~.ListContextsRequest], + ~.ListContextsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_contexts' not in self._stubs: + self._stubs['list_contexts'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Contexts/ListContexts', + request_serializer=context.ListContextsRequest.serialize, + response_deserializer=context.ListContextsResponse.deserialize, + ) + return self._stubs['list_contexts'] + + @property + def get_context(self) -> Callable[ + [context.GetContextRequest], + context.Context]: + r"""Return a callable for the get context method over gRPC. + + Retrieves the specified context. + + Returns: + Callable[[~.GetContextRequest], + ~.Context]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_context' not in self._stubs: + self._stubs['get_context'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Contexts/GetContext', + request_serializer=context.GetContextRequest.serialize, + response_deserializer=context.Context.deserialize, + ) + return self._stubs['get_context'] + + @property + def create_context(self) -> Callable[ + [gcd_context.CreateContextRequest], + gcd_context.Context]: + r"""Return a callable for the create context method over gRPC. + + Creates a context. + If the specified context already exists, overrides the + context. + + Returns: + Callable[[~.CreateContextRequest], + ~.Context]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_context' not in self._stubs: + self._stubs['create_context'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Contexts/CreateContext', + request_serializer=gcd_context.CreateContextRequest.serialize, + response_deserializer=gcd_context.Context.deserialize, + ) + return self._stubs['create_context'] + + @property + def update_context(self) -> Callable[ + [gcd_context.UpdateContextRequest], + gcd_context.Context]: + r"""Return a callable for the update context method over gRPC. + + Updates the specified context. + + Returns: + Callable[[~.UpdateContextRequest], + ~.Context]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_context' not in self._stubs: + self._stubs['update_context'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Contexts/UpdateContext', + request_serializer=gcd_context.UpdateContextRequest.serialize, + response_deserializer=gcd_context.Context.deserialize, + ) + return self._stubs['update_context'] + + @property + def delete_context(self) -> Callable[ + [context.DeleteContextRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete context method over gRPC. + + Deletes the specified context. + + Returns: + Callable[[~.DeleteContextRequest], + ~.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_context' not in self._stubs: + self._stubs['delete_context'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Contexts/DeleteContext', + request_serializer=context.DeleteContextRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_context'] + + @property + def delete_all_contexts(self) -> Callable[ + [context.DeleteAllContextsRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete all contexts method over gRPC. + + Deletes all active contexts in the specified session. + + Returns: + Callable[[~.DeleteAllContextsRequest], + ~.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_all_contexts' not in self._stubs: + self._stubs['delete_all_contexts'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Contexts/DeleteAllContexts', + request_serializer=context.DeleteAllContextsRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_all_contexts'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'ContextsGrpcTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc_asyncio.py new file mode 100644 index 000000000..4cd78858a --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc_asyncio.py @@ -0,0 +1,394 @@ +# -*- 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 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import context +from google.cloud.dialogflow_v2beta1.types import context as gcd_context +from google.protobuf import empty_pb2 # type: ignore +from .base import ContextsTransport, DEFAULT_CLIENT_INFO +from .grpc import ContextsGrpcTransport + + +class ContextsGrpcAsyncIOTransport(ContextsTransport): + """gRPC AsyncIO backend transport for Contexts. + + Service for managing + [Contexts][google.cloud.dialogflow.v2beta1.Context]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 list_contexts(self) -> Callable[ + [context.ListContextsRequest], + Awaitable[context.ListContextsResponse]]: + r"""Return a callable for the list contexts method over gRPC. + + Returns the list of all contexts in the specified + session. + + Returns: + Callable[[~.ListContextsRequest], + Awaitable[~.ListContextsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_contexts' not in self._stubs: + self._stubs['list_contexts'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Contexts/ListContexts', + request_serializer=context.ListContextsRequest.serialize, + response_deserializer=context.ListContextsResponse.deserialize, + ) + return self._stubs['list_contexts'] + + @property + def get_context(self) -> Callable[ + [context.GetContextRequest], + Awaitable[context.Context]]: + r"""Return a callable for the get context method over gRPC. + + Retrieves the specified context. + + Returns: + Callable[[~.GetContextRequest], + Awaitable[~.Context]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_context' not in self._stubs: + self._stubs['get_context'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Contexts/GetContext', + request_serializer=context.GetContextRequest.serialize, + response_deserializer=context.Context.deserialize, + ) + return self._stubs['get_context'] + + @property + def create_context(self) -> Callable[ + [gcd_context.CreateContextRequest], + Awaitable[gcd_context.Context]]: + r"""Return a callable for the create context method over gRPC. + + Creates a context. + If the specified context already exists, overrides the + context. + + Returns: + Callable[[~.CreateContextRequest], + Awaitable[~.Context]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_context' not in self._stubs: + self._stubs['create_context'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Contexts/CreateContext', + request_serializer=gcd_context.CreateContextRequest.serialize, + response_deserializer=gcd_context.Context.deserialize, + ) + return self._stubs['create_context'] + + @property + def update_context(self) -> Callable[ + [gcd_context.UpdateContextRequest], + Awaitable[gcd_context.Context]]: + r"""Return a callable for the update context method over gRPC. + + Updates the specified context. + + Returns: + Callable[[~.UpdateContextRequest], + Awaitable[~.Context]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_context' not in self._stubs: + self._stubs['update_context'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Contexts/UpdateContext', + request_serializer=gcd_context.UpdateContextRequest.serialize, + response_deserializer=gcd_context.Context.deserialize, + ) + return self._stubs['update_context'] + + @property + def delete_context(self) -> Callable[ + [context.DeleteContextRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete context method over gRPC. + + Deletes the specified context. + + Returns: + Callable[[~.DeleteContextRequest], + 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_context' not in self._stubs: + self._stubs['delete_context'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Contexts/DeleteContext', + request_serializer=context.DeleteContextRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_context'] + + @property + def delete_all_contexts(self) -> Callable[ + [context.DeleteAllContextsRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete all contexts method over gRPC. + + Deletes all active contexts in the specified session. + + Returns: + Callable[[~.DeleteAllContextsRequest], + 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_all_contexts' not in self._stubs: + self._stubs['delete_all_contexts'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Contexts/DeleteAllContexts', + request_serializer=context.DeleteAllContextsRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_all_contexts'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ContextsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/__init__.py new file mode 100644 index 000000000..3e8e4ea19 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/__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 ConversationProfilesClient +from .async_client import ConversationProfilesAsyncClient + +__all__ = ( + 'ConversationProfilesClient', + 'ConversationProfilesAsyncClient', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/async_client.py new file mode 100644 index 000000000..ac1dd129c --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/async_client.py @@ -0,0 +1,603 @@ +# -*- 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 + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2beta1.services.conversation_profiles import pagers +from google.cloud.dialogflow_v2beta1.types import audio_config +from google.cloud.dialogflow_v2beta1.types import conversation_profile +from google.cloud.dialogflow_v2beta1.types import conversation_profile as gcd_conversation_profile +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ConversationProfilesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ConversationProfilesGrpcAsyncIOTransport +from .client import ConversationProfilesClient + + +class ConversationProfilesAsyncClient: + """Service for managing + [ConversationProfiles][google.cloud.dialogflow.v2beta1.ConversationProfile]. + """ + + _client: ConversationProfilesClient + + DEFAULT_ENDPOINT = ConversationProfilesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ConversationProfilesClient.DEFAULT_MTLS_ENDPOINT + + agent_path = staticmethod(ConversationProfilesClient.agent_path) + parse_agent_path = staticmethod(ConversationProfilesClient.parse_agent_path) + conversation_model_path = staticmethod(ConversationProfilesClient.conversation_model_path) + parse_conversation_model_path = staticmethod(ConversationProfilesClient.parse_conversation_model_path) + conversation_profile_path = staticmethod(ConversationProfilesClient.conversation_profile_path) + parse_conversation_profile_path = staticmethod(ConversationProfilesClient.parse_conversation_profile_path) + cx_security_settings_path = staticmethod(ConversationProfilesClient.cx_security_settings_path) + parse_cx_security_settings_path = staticmethod(ConversationProfilesClient.parse_cx_security_settings_path) + document_path = staticmethod(ConversationProfilesClient.document_path) + parse_document_path = staticmethod(ConversationProfilesClient.parse_document_path) + knowledge_base_path = staticmethod(ConversationProfilesClient.knowledge_base_path) + parse_knowledge_base_path = staticmethod(ConversationProfilesClient.parse_knowledge_base_path) + common_billing_account_path = staticmethod(ConversationProfilesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ConversationProfilesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ConversationProfilesClient.common_folder_path) + parse_common_folder_path = staticmethod(ConversationProfilesClient.parse_common_folder_path) + common_organization_path = staticmethod(ConversationProfilesClient.common_organization_path) + parse_common_organization_path = staticmethod(ConversationProfilesClient.parse_common_organization_path) + common_project_path = staticmethod(ConversationProfilesClient.common_project_path) + parse_common_project_path = staticmethod(ConversationProfilesClient.parse_common_project_path) + common_location_path = staticmethod(ConversationProfilesClient.common_location_path) + parse_common_location_path = staticmethod(ConversationProfilesClient.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: + ConversationProfilesAsyncClient: The constructed client. + """ + return ConversationProfilesClient.from_service_account_info.__func__(ConversationProfilesAsyncClient, 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: + ConversationProfilesAsyncClient: The constructed client. + """ + return ConversationProfilesClient.from_service_account_file.__func__(ConversationProfilesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ConversationProfilesTransport: + """Returns the transport used by the client instance. + + Returns: + ConversationProfilesTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ConversationProfilesClient).get_transport_class, type(ConversationProfilesClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ConversationProfilesTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the conversation profiles 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, ~.ConversationProfilesTransport]): 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 = ConversationProfilesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_conversation_profiles(self, + request: Union[conversation_profile.ListConversationProfilesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListConversationProfilesAsyncPager: + r"""Returns the list of all conversation profiles in the + specified project. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListConversationProfilesRequest, dict]): + The request object. The request message for + [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2beta1.ConversationProfiles.ListConversationProfiles]. + parent (:class:`str`): + Required. The project to list all conversation profiles + from. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.services.conversation_profiles.pagers.ListConversationProfilesAsyncPager: + The response message for + [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2beta1.ConversationProfiles.ListConversationProfiles]. + + 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 = conversation_profile.ListConversationProfilesRequest(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_conversation_profiles, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListConversationProfilesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_conversation_profile(self, + request: Union[conversation_profile.GetConversationProfileRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation_profile.ConversationProfile: + r"""Retrieves the specified conversation profile. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetConversationProfileRequest, dict]): + The request object. The request message for + [ConversationProfiles.GetConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.GetConversationProfile]. + name (:class:`str`): + Required. The resource name of the conversation profile. + Format: + ``projects//locations//conversationProfiles/``. + + 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.dialogflow_v2beta1.types.ConversationProfile: + Defines the services to connect to + incoming Dialogflow conversations. + + """ + # 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 = conversation_profile.GetConversationProfileRequest(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_conversation_profile, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_conversation_profile(self, + request: Union[gcd_conversation_profile.CreateConversationProfileRequest, dict] = None, + *, + parent: str = None, + conversation_profile: gcd_conversation_profile.ConversationProfile = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_conversation_profile.ConversationProfile: + r"""Creates a conversation profile in the specified project. + + [ConversationProfile.CreateTime][] and + [ConversationProfile.UpdateTime][] aren't populated in the + response. You can retrieve them via + [GetConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.GetConversationProfile] + API. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.CreateConversationProfileRequest, dict]): + The request object. The request message for + [ConversationProfiles.CreateConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.CreateConversationProfile]. + parent (:class:`str`): + Required. The project to create a conversation profile + for. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + conversation_profile (:class:`google.cloud.dialogflow_v2beta1.types.ConversationProfile`): + Required. The conversation profile to + create. + + This corresponds to the ``conversation_profile`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.ConversationProfile: + Defines the services to connect to + incoming Dialogflow conversations. + + """ + # 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, conversation_profile]) + if request is 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 = gcd_conversation_profile.CreateConversationProfileRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if conversation_profile is not None: + request.conversation_profile = conversation_profile + + # 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_conversation_profile, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_conversation_profile(self, + request: Union[gcd_conversation_profile.UpdateConversationProfileRequest, dict] = None, + *, + conversation_profile: gcd_conversation_profile.ConversationProfile = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_conversation_profile.ConversationProfile: + r"""Updates the specified conversation profile. + + [ConversationProfile.CreateTime][] and + [ConversationProfile.UpdateTime][] aren't populated in the + response. You can retrieve them via + [GetConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.GetConversationProfile] + API. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.UpdateConversationProfileRequest, dict]): + The request object. The request message for + [ConversationProfiles.UpdateConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.UpdateConversationProfile]. + conversation_profile (:class:`google.cloud.dialogflow_v2beta1.types.ConversationProfile`): + Required. The conversation profile to + update. + + This corresponds to the ``conversation_profile`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The mask to control which + fields to update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.ConversationProfile: + Defines the services to connect to + incoming Dialogflow conversations. + + """ + # 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([conversation_profile, 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 = gcd_conversation_profile.UpdateConversationProfileRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if conversation_profile is not None: + request.conversation_profile = conversation_profile + 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_conversation_profile, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("conversation_profile.name", request.conversation_profile.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_conversation_profile(self, + request: Union[conversation_profile.DeleteConversationProfileRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified conversation profile. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.DeleteConversationProfileRequest, dict]): + The request object. The request message for + [ConversationProfiles.DeleteConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.DeleteConversationProfile]. + This operation fails if the conversation profile is + still referenced from a phone number. + name (:class:`str`): + Required. The name of the conversation profile to + delete. Format: + ``projects//locations//conversationProfiles/``. + + 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 = conversation_profile.DeleteConversationProfileRequest(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_conversation_profile, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ConversationProfilesAsyncClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/client.py new file mode 100644 index 000000000..4a1a5d0a3 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/client.py @@ -0,0 +1,846 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2beta1.services.conversation_profiles import pagers +from google.cloud.dialogflow_v2beta1.types import audio_config +from google.cloud.dialogflow_v2beta1.types import conversation_profile +from google.cloud.dialogflow_v2beta1.types import conversation_profile as gcd_conversation_profile +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ConversationProfilesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ConversationProfilesGrpcTransport +from .transports.grpc_asyncio import ConversationProfilesGrpcAsyncIOTransport + + +class ConversationProfilesClientMeta(type): + """Metaclass for the ConversationProfiles 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[ConversationProfilesTransport]] + _transport_registry["grpc"] = ConversationProfilesGrpcTransport + _transport_registry["grpc_asyncio"] = ConversationProfilesGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ConversationProfilesTransport]: + """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 ConversationProfilesClient(metaclass=ConversationProfilesClientMeta): + """Service for managing + [ConversationProfiles][google.cloud.dialogflow.v2beta1.ConversationProfile]. + """ + + @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 = "dialogflow.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: + ConversationProfilesClient: 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: + ConversationProfilesClient: 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) -> ConversationProfilesTransport: + """Returns the transport used by the client instance. + + Returns: + ConversationProfilesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def agent_path(project: str,) -> str: + """Returns a fully-qualified agent string.""" + return "projects/{project}/agent".format(project=project, ) + + @staticmethod + def parse_agent_path(path: str) -> Dict[str,str]: + """Parses a agent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent$", path) + return m.groupdict() if m else {} + + @staticmethod + def conversation_model_path(project: str,location: str,conversation_model: str,) -> str: + """Returns a fully-qualified conversation_model string.""" + return "projects/{project}/locations/{location}/conversationModels/{conversation_model}".format(project=project, location=location, conversation_model=conversation_model, ) + + @staticmethod + def parse_conversation_model_path(path: str) -> Dict[str,str]: + """Parses a conversation_model path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/conversationModels/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def conversation_profile_path(project: str,conversation_profile: str,) -> str: + """Returns a fully-qualified conversation_profile string.""" + return "projects/{project}/conversationProfiles/{conversation_profile}".format(project=project, conversation_profile=conversation_profile, ) + + @staticmethod + def parse_conversation_profile_path(path: str) -> Dict[str,str]: + """Parses a conversation_profile path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/conversationProfiles/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def cx_security_settings_path(project: str,location: str,security_settings: str,) -> str: + """Returns a fully-qualified cx_security_settings string.""" + return "projects/{project}/locations/{location}/securitySettings/{security_settings}".format(project=project, location=location, security_settings=security_settings, ) + + @staticmethod + def parse_cx_security_settings_path(path: str) -> Dict[str,str]: + """Parses a cx_security_settings path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/securitySettings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def document_path(project: str,knowledge_base: str,document: str,) -> str: + """Returns a fully-qualified document string.""" + return "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format(project=project, knowledge_base=knowledge_base, document=document, ) + + @staticmethod + def parse_document_path(path: str) -> Dict[str,str]: + """Parses a document path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/knowledgeBases/(?P.+?)/documents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def knowledge_base_path(project: str,knowledge_base: str,) -> str: + """Returns a fully-qualified knowledge_base string.""" + return "projects/{project}/knowledgeBases/{knowledge_base}".format(project=project, knowledge_base=knowledge_base, ) + + @staticmethod + def parse_knowledge_base_path(path: str) -> Dict[str,str]: + """Parses a knowledge_base path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/knowledgeBases/(?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, ConversationProfilesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the conversation profiles 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, ConversationProfilesTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, ConversationProfilesTransport): + # transport is a ConversationProfilesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_conversation_profiles(self, + request: Union[conversation_profile.ListConversationProfilesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListConversationProfilesPager: + r"""Returns the list of all conversation profiles in the + specified project. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListConversationProfilesRequest, dict]): + The request object. The request message for + [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2beta1.ConversationProfiles.ListConversationProfiles]. + parent (str): + Required. The project to list all conversation profiles + from. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.services.conversation_profiles.pagers.ListConversationProfilesPager: + The response message for + [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2beta1.ConversationProfiles.ListConversationProfiles]. + + 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 conversation_profile.ListConversationProfilesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversation_profile.ListConversationProfilesRequest): + request = conversation_profile.ListConversationProfilesRequest(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_conversation_profiles] + + # Certain 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.ListConversationProfilesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_conversation_profile(self, + request: Union[conversation_profile.GetConversationProfileRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation_profile.ConversationProfile: + r"""Retrieves the specified conversation profile. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetConversationProfileRequest, dict]): + The request object. The request message for + [ConversationProfiles.GetConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.GetConversationProfile]. + name (str): + Required. The resource name of the conversation profile. + Format: + ``projects//locations//conversationProfiles/``. + + 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.dialogflow_v2beta1.types.ConversationProfile: + Defines the services to connect to + incoming Dialogflow conversations. + + """ + # 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 conversation_profile.GetConversationProfileRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversation_profile.GetConversationProfileRequest): + request = conversation_profile.GetConversationProfileRequest(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_conversation_profile] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_conversation_profile(self, + request: Union[gcd_conversation_profile.CreateConversationProfileRequest, dict] = None, + *, + parent: str = None, + conversation_profile: gcd_conversation_profile.ConversationProfile = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_conversation_profile.ConversationProfile: + r"""Creates a conversation profile in the specified project. + + [ConversationProfile.CreateTime][] and + [ConversationProfile.UpdateTime][] aren't populated in the + response. You can retrieve them via + [GetConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.GetConversationProfile] + API. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.CreateConversationProfileRequest, dict]): + The request object. The request message for + [ConversationProfiles.CreateConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.CreateConversationProfile]. + parent (str): + Required. The project to create a conversation profile + for. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + conversation_profile (google.cloud.dialogflow_v2beta1.types.ConversationProfile): + Required. The conversation profile to + create. + + This corresponds to the ``conversation_profile`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.ConversationProfile: + Defines the services to connect to + incoming Dialogflow conversations. + + """ + # 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, conversation_profile]) + if request is 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 gcd_conversation_profile.CreateConversationProfileRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_conversation_profile.CreateConversationProfileRequest): + request = gcd_conversation_profile.CreateConversationProfileRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if conversation_profile is not None: + request.conversation_profile = conversation_profile + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_conversation_profile] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_conversation_profile(self, + request: Union[gcd_conversation_profile.UpdateConversationProfileRequest, dict] = None, + *, + conversation_profile: gcd_conversation_profile.ConversationProfile = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_conversation_profile.ConversationProfile: + r"""Updates the specified conversation profile. + + [ConversationProfile.CreateTime][] and + [ConversationProfile.UpdateTime][] aren't populated in the + response. You can retrieve them via + [GetConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.GetConversationProfile] + API. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.UpdateConversationProfileRequest, dict]): + The request object. The request message for + [ConversationProfiles.UpdateConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.UpdateConversationProfile]. + conversation_profile (google.cloud.dialogflow_v2beta1.types.ConversationProfile): + Required. The conversation profile to + update. + + This corresponds to the ``conversation_profile`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which + fields to update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.ConversationProfile: + Defines the services to connect to + incoming Dialogflow conversations. + + """ + # 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([conversation_profile, 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 gcd_conversation_profile.UpdateConversationProfileRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_conversation_profile.UpdateConversationProfileRequest): + request = gcd_conversation_profile.UpdateConversationProfileRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if conversation_profile is not None: + request.conversation_profile = conversation_profile + 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_conversation_profile] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("conversation_profile.name", request.conversation_profile.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_conversation_profile(self, + request: Union[conversation_profile.DeleteConversationProfileRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified conversation profile. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.DeleteConversationProfileRequest, dict]): + The request object. The request message for + [ConversationProfiles.DeleteConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.DeleteConversationProfile]. + This operation fails if the conversation profile is + still referenced from a phone number. + name (str): + Required. The name of the conversation profile to + delete. Format: + ``projects//locations//conversationProfiles/``. + + 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 conversation_profile.DeleteConversationProfileRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversation_profile.DeleteConversationProfileRequest): + request = conversation_profile.DeleteConversationProfileRequest(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_conversation_profile] + + # Certain 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 __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ConversationProfilesClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/pagers.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/pagers.py new file mode 100644 index 000000000..6720d2b2b --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflow_v2beta1.types import conversation_profile + + +class ListConversationProfilesPager: + """A pager for iterating through ``list_conversation_profiles`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListConversationProfilesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``conversation_profiles`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListConversationProfiles`` requests and continue to iterate + through the ``conversation_profiles`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListConversationProfilesResponse` + 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[..., conversation_profile.ListConversationProfilesResponse], + request: conversation_profile.ListConversationProfilesRequest, + response: conversation_profile.ListConversationProfilesResponse, + *, + 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.dialogflow_v2beta1.types.ListConversationProfilesRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListConversationProfilesResponse): + 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 = conversation_profile.ListConversationProfilesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[conversation_profile.ListConversationProfilesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[conversation_profile.ConversationProfile]: + for page in self.pages: + yield from page.conversation_profiles + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListConversationProfilesAsyncPager: + """A pager for iterating through ``list_conversation_profiles`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListConversationProfilesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``conversation_profiles`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListConversationProfiles`` requests and continue to iterate + through the ``conversation_profiles`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListConversationProfilesResponse` + 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[conversation_profile.ListConversationProfilesResponse]], + request: conversation_profile.ListConversationProfilesRequest, + response: conversation_profile.ListConversationProfilesResponse, + *, + 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.dialogflow_v2beta1.types.ListConversationProfilesRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListConversationProfilesResponse): + 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 = conversation_profile.ListConversationProfilesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[conversation_profile.ListConversationProfilesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[conversation_profile.ConversationProfile]: + async def async_generator(): + async for page in self.pages: + for response in page.conversation_profiles: + 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/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/__init__.py new file mode 100644 index 000000000..19a679f49 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/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 ConversationProfilesTransport +from .grpc import ConversationProfilesGrpcTransport +from .grpc_asyncio import ConversationProfilesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ConversationProfilesTransport]] +_transport_registry['grpc'] = ConversationProfilesGrpcTransport +_transport_registry['grpc_asyncio'] = ConversationProfilesGrpcAsyncIOTransport + +__all__ = ( + 'ConversationProfilesTransport', + 'ConversationProfilesGrpcTransport', + 'ConversationProfilesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/base.py new file mode 100644 index 000000000..625a9d0f0 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/base.py @@ -0,0 +1,205 @@ +# -*- 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.types import conversation_profile +from google.cloud.dialogflow_v2beta1.types import conversation_profile as gcd_conversation_profile +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-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ConversationProfilesTransport(abc.ABC): + """Abstract transport class for ConversationProfiles.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_conversation_profiles: gapic_v1.method.wrap_method( + self.list_conversation_profiles, + default_timeout=None, + client_info=client_info, + ), + self.get_conversation_profile: gapic_v1.method.wrap_method( + self.get_conversation_profile, + default_timeout=None, + client_info=client_info, + ), + self.create_conversation_profile: gapic_v1.method.wrap_method( + self.create_conversation_profile, + default_timeout=None, + client_info=client_info, + ), + self.update_conversation_profile: gapic_v1.method.wrap_method( + self.update_conversation_profile, + default_timeout=None, + client_info=client_info, + ), + self.delete_conversation_profile: gapic_v1.method.wrap_method( + self.delete_conversation_profile, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_conversation_profiles(self) -> Callable[ + [conversation_profile.ListConversationProfilesRequest], + Union[ + conversation_profile.ListConversationProfilesResponse, + Awaitable[conversation_profile.ListConversationProfilesResponse] + ]]: + raise NotImplementedError() + + @property + def get_conversation_profile(self) -> Callable[ + [conversation_profile.GetConversationProfileRequest], + Union[ + conversation_profile.ConversationProfile, + Awaitable[conversation_profile.ConversationProfile] + ]]: + raise NotImplementedError() + + @property + def create_conversation_profile(self) -> Callable[ + [gcd_conversation_profile.CreateConversationProfileRequest], + Union[ + gcd_conversation_profile.ConversationProfile, + Awaitable[gcd_conversation_profile.ConversationProfile] + ]]: + raise NotImplementedError() + + @property + def update_conversation_profile(self) -> Callable[ + [gcd_conversation_profile.UpdateConversationProfileRequest], + Union[ + gcd_conversation_profile.ConversationProfile, + Awaitable[gcd_conversation_profile.ConversationProfile] + ]]: + raise NotImplementedError() + + @property + def delete_conversation_profile(self) -> Callable[ + [conversation_profile.DeleteConversationProfileRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'ConversationProfilesTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc.py new file mode 100644 index 000000000..60fbcefc2 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc.py @@ -0,0 +1,374 @@ +# -*- 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 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import conversation_profile +from google.cloud.dialogflow_v2beta1.types import conversation_profile as gcd_conversation_profile +from google.protobuf import empty_pb2 # type: ignore +from .base import ConversationProfilesTransport, DEFAULT_CLIENT_INFO + + +class ConversationProfilesGrpcTransport(ConversationProfilesTransport): + """gRPC backend transport for ConversationProfiles. + + Service for managing + [ConversationProfiles][google.cloud.dialogflow.v2beta1.ConversationProfile]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 = 'dialogflow.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 list_conversation_profiles(self) -> Callable[ + [conversation_profile.ListConversationProfilesRequest], + conversation_profile.ListConversationProfilesResponse]: + r"""Return a callable for the list conversation profiles method over gRPC. + + Returns the list of all conversation profiles in the + specified project. + + Returns: + Callable[[~.ListConversationProfilesRequest], + ~.ListConversationProfilesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation_profiles' not in self._stubs: + self._stubs['list_conversation_profiles'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.ConversationProfiles/ListConversationProfiles', + request_serializer=conversation_profile.ListConversationProfilesRequest.serialize, + response_deserializer=conversation_profile.ListConversationProfilesResponse.deserialize, + ) + return self._stubs['list_conversation_profiles'] + + @property + def get_conversation_profile(self) -> Callable[ + [conversation_profile.GetConversationProfileRequest], + conversation_profile.ConversationProfile]: + r"""Return a callable for the get conversation profile method over gRPC. + + Retrieves the specified conversation profile. + + Returns: + Callable[[~.GetConversationProfileRequest], + ~.ConversationProfile]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation_profile' not in self._stubs: + self._stubs['get_conversation_profile'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.ConversationProfiles/GetConversationProfile', + request_serializer=conversation_profile.GetConversationProfileRequest.serialize, + response_deserializer=conversation_profile.ConversationProfile.deserialize, + ) + return self._stubs['get_conversation_profile'] + + @property + def create_conversation_profile(self) -> Callable[ + [gcd_conversation_profile.CreateConversationProfileRequest], + gcd_conversation_profile.ConversationProfile]: + r"""Return a callable for the create conversation profile method over gRPC. + + Creates a conversation profile in the specified project. + + [ConversationProfile.CreateTime][] and + [ConversationProfile.UpdateTime][] aren't populated in the + response. You can retrieve them via + [GetConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.GetConversationProfile] + API. + + Returns: + Callable[[~.CreateConversationProfileRequest], + ~.ConversationProfile]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation_profile' not in self._stubs: + self._stubs['create_conversation_profile'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.ConversationProfiles/CreateConversationProfile', + request_serializer=gcd_conversation_profile.CreateConversationProfileRequest.serialize, + response_deserializer=gcd_conversation_profile.ConversationProfile.deserialize, + ) + return self._stubs['create_conversation_profile'] + + @property + def update_conversation_profile(self) -> Callable[ + [gcd_conversation_profile.UpdateConversationProfileRequest], + gcd_conversation_profile.ConversationProfile]: + r"""Return a callable for the update conversation profile method over gRPC. + + Updates the specified conversation profile. + + [ConversationProfile.CreateTime][] and + [ConversationProfile.UpdateTime][] aren't populated in the + response. You can retrieve them via + [GetConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.GetConversationProfile] + API. + + Returns: + Callable[[~.UpdateConversationProfileRequest], + ~.ConversationProfile]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation_profile' not in self._stubs: + self._stubs['update_conversation_profile'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.ConversationProfiles/UpdateConversationProfile', + request_serializer=gcd_conversation_profile.UpdateConversationProfileRequest.serialize, + response_deserializer=gcd_conversation_profile.ConversationProfile.deserialize, + ) + return self._stubs['update_conversation_profile'] + + @property + def delete_conversation_profile(self) -> Callable[ + [conversation_profile.DeleteConversationProfileRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete conversation profile method over gRPC. + + Deletes the specified conversation profile. + + Returns: + Callable[[~.DeleteConversationProfileRequest], + ~.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_conversation_profile' not in self._stubs: + self._stubs['delete_conversation_profile'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.ConversationProfiles/DeleteConversationProfile', + request_serializer=conversation_profile.DeleteConversationProfileRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_conversation_profile'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'ConversationProfilesGrpcTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc_asyncio.py new file mode 100644 index 000000000..7d2623e77 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc_asyncio.py @@ -0,0 +1,378 @@ +# -*- 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 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import conversation_profile +from google.cloud.dialogflow_v2beta1.types import conversation_profile as gcd_conversation_profile +from google.protobuf import empty_pb2 # type: ignore +from .base import ConversationProfilesTransport, DEFAULT_CLIENT_INFO +from .grpc import ConversationProfilesGrpcTransport + + +class ConversationProfilesGrpcAsyncIOTransport(ConversationProfilesTransport): + """gRPC AsyncIO backend transport for ConversationProfiles. + + Service for managing + [ConversationProfiles][google.cloud.dialogflow.v2beta1.ConversationProfile]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 list_conversation_profiles(self) -> Callable[ + [conversation_profile.ListConversationProfilesRequest], + Awaitable[conversation_profile.ListConversationProfilesResponse]]: + r"""Return a callable for the list conversation profiles method over gRPC. + + Returns the list of all conversation profiles in the + specified project. + + Returns: + Callable[[~.ListConversationProfilesRequest], + Awaitable[~.ListConversationProfilesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation_profiles' not in self._stubs: + self._stubs['list_conversation_profiles'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.ConversationProfiles/ListConversationProfiles', + request_serializer=conversation_profile.ListConversationProfilesRequest.serialize, + response_deserializer=conversation_profile.ListConversationProfilesResponse.deserialize, + ) + return self._stubs['list_conversation_profiles'] + + @property + def get_conversation_profile(self) -> Callable[ + [conversation_profile.GetConversationProfileRequest], + Awaitable[conversation_profile.ConversationProfile]]: + r"""Return a callable for the get conversation profile method over gRPC. + + Retrieves the specified conversation profile. + + Returns: + Callable[[~.GetConversationProfileRequest], + Awaitable[~.ConversationProfile]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation_profile' not in self._stubs: + self._stubs['get_conversation_profile'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.ConversationProfiles/GetConversationProfile', + request_serializer=conversation_profile.GetConversationProfileRequest.serialize, + response_deserializer=conversation_profile.ConversationProfile.deserialize, + ) + return self._stubs['get_conversation_profile'] + + @property + def create_conversation_profile(self) -> Callable[ + [gcd_conversation_profile.CreateConversationProfileRequest], + Awaitable[gcd_conversation_profile.ConversationProfile]]: + r"""Return a callable for the create conversation profile method over gRPC. + + Creates a conversation profile in the specified project. + + [ConversationProfile.CreateTime][] and + [ConversationProfile.UpdateTime][] aren't populated in the + response. You can retrieve them via + [GetConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.GetConversationProfile] + API. + + Returns: + Callable[[~.CreateConversationProfileRequest], + Awaitable[~.ConversationProfile]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation_profile' not in self._stubs: + self._stubs['create_conversation_profile'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.ConversationProfiles/CreateConversationProfile', + request_serializer=gcd_conversation_profile.CreateConversationProfileRequest.serialize, + response_deserializer=gcd_conversation_profile.ConversationProfile.deserialize, + ) + return self._stubs['create_conversation_profile'] + + @property + def update_conversation_profile(self) -> Callable[ + [gcd_conversation_profile.UpdateConversationProfileRequest], + Awaitable[gcd_conversation_profile.ConversationProfile]]: + r"""Return a callable for the update conversation profile method over gRPC. + + Updates the specified conversation profile. + + [ConversationProfile.CreateTime][] and + [ConversationProfile.UpdateTime][] aren't populated in the + response. You can retrieve them via + [GetConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.GetConversationProfile] + API. + + Returns: + Callable[[~.UpdateConversationProfileRequest], + Awaitable[~.ConversationProfile]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation_profile' not in self._stubs: + self._stubs['update_conversation_profile'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.ConversationProfiles/UpdateConversationProfile', + request_serializer=gcd_conversation_profile.UpdateConversationProfileRequest.serialize, + response_deserializer=gcd_conversation_profile.ConversationProfile.deserialize, + ) + return self._stubs['update_conversation_profile'] + + @property + def delete_conversation_profile(self) -> Callable[ + [conversation_profile.DeleteConversationProfileRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete conversation profile method over gRPC. + + Deletes the specified conversation profile. + + Returns: + Callable[[~.DeleteConversationProfileRequest], + 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_conversation_profile' not in self._stubs: + self._stubs['delete_conversation_profile'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.ConversationProfiles/DeleteConversationProfile', + request_serializer=conversation_profile.DeleteConversationProfileRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_conversation_profile'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ConversationProfilesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/__init__.py new file mode 100644 index 000000000..0445da9c4 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/__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 ConversationsClient +from .async_client import ConversationsAsyncClient + +__all__ = ( + 'ConversationsClient', + 'ConversationsAsyncClient', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/async_client.py new file mode 100644 index 000000000..7bd363baa --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/async_client.py @@ -0,0 +1,710 @@ +# -*- 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 + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2beta1.services.conversations import pagers +from google.cloud.dialogflow_v2beta1.types import conversation +from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation +from google.cloud.dialogflow_v2beta1.types import participant +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ConversationsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ConversationsGrpcAsyncIOTransport +from .client import ConversationsClient + + +class ConversationsAsyncClient: + """Service for managing + [Conversations][google.cloud.dialogflow.v2beta1.Conversation]. + """ + + _client: ConversationsClient + + DEFAULT_ENDPOINT = ConversationsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ConversationsClient.DEFAULT_MTLS_ENDPOINT + + conversation_path = staticmethod(ConversationsClient.conversation_path) + parse_conversation_path = staticmethod(ConversationsClient.parse_conversation_path) + conversation_profile_path = staticmethod(ConversationsClient.conversation_profile_path) + parse_conversation_profile_path = staticmethod(ConversationsClient.parse_conversation_profile_path) + message_path = staticmethod(ConversationsClient.message_path) + parse_message_path = staticmethod(ConversationsClient.parse_message_path) + common_billing_account_path = staticmethod(ConversationsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ConversationsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ConversationsClient.common_folder_path) + parse_common_folder_path = staticmethod(ConversationsClient.parse_common_folder_path) + common_organization_path = staticmethod(ConversationsClient.common_organization_path) + parse_common_organization_path = staticmethod(ConversationsClient.parse_common_organization_path) + common_project_path = staticmethod(ConversationsClient.common_project_path) + parse_common_project_path = staticmethod(ConversationsClient.parse_common_project_path) + common_location_path = staticmethod(ConversationsClient.common_location_path) + parse_common_location_path = staticmethod(ConversationsClient.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: + ConversationsAsyncClient: The constructed client. + """ + return ConversationsClient.from_service_account_info.__func__(ConversationsAsyncClient, 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: + ConversationsAsyncClient: The constructed client. + """ + return ConversationsClient.from_service_account_file.__func__(ConversationsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ConversationsTransport: + """Returns the transport used by the client instance. + + Returns: + ConversationsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ConversationsClient).get_transport_class, type(ConversationsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ConversationsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the conversations 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, ~.ConversationsTransport]): 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 = ConversationsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_conversation(self, + request: Union[gcd_conversation.CreateConversationRequest, dict] = None, + *, + parent: str = None, + conversation: gcd_conversation.Conversation = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_conversation.Conversation: + r"""Creates a new conversation. Conversations are auto-completed + after 24 hours. + + Conversation Lifecycle: There are two stages during a + conversation: Automated Agent Stage and Assist Stage. + + For Automated Agent Stage, there will be a dialogflow agent + responding to user queries. + + For Assist Stage, there's no dialogflow agent responding to user + queries. But we will provide suggestions which are generated + from conversation. + + If + [Conversation.conversation_profile][google.cloud.dialogflow.v2beta1.Conversation.conversation_profile] + is configured for a dialogflow agent, conversation will start + from ``Automated Agent Stage``, otherwise, it will start from + ``Assist Stage``. And during ``Automated Agent Stage``, once an + [Intent][google.cloud.dialogflow.v2beta1.Intent] with + [Intent.live_agent_handoff][google.cloud.dialogflow.v2beta1.Intent.live_agent_handoff] + is triggered, conversation will transfer to Assist Stage. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.CreateConversationRequest, dict]): + The request object. The request message for + [Conversations.CreateConversation][google.cloud.dialogflow.v2beta1.Conversations.CreateConversation]. + parent (:class:`str`): + Required. Resource identifier of the project creating + the conversation. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + conversation (:class:`google.cloud.dialogflow_v2beta1.types.Conversation`): + Required. The conversation to create. + This corresponds to the ``conversation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Conversation: + Represents a conversation. + A conversation is an interaction between + an agent, including live agents and + Dialogflow agents, and a support + customer. Conversations can include + phone calls and text-based chat + sessions. + + """ + # 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, conversation]) + if request is 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 = gcd_conversation.CreateConversationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if conversation is not None: + request.conversation = conversation + + # 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_conversation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_conversations(self, + request: Union[conversation.ListConversationsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListConversationsAsyncPager: + r"""Returns the list of all conversations in the + specified project. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListConversationsRequest, dict]): + The request object. The request message for + [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. + parent (:class:`str`): + Required. The project from which to list all + conversation. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.services.conversations.pagers.ListConversationsAsyncPager: + The response message for + [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. + + 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 = conversation.ListConversationsRequest(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_conversations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListConversationsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_conversation(self, + request: Union[conversation.GetConversationRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation.Conversation: + r"""Retrieves the specific conversation. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetConversationRequest, dict]): + The request object. The request message for + [Conversations.GetConversation][google.cloud.dialogflow.v2beta1.Conversations.GetConversation]. + name (:class:`str`): + Required. The name of the conversation. Format: + ``projects//locations//conversations/``. + + 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.dialogflow_v2beta1.types.Conversation: + Represents a conversation. + A conversation is an interaction between + an agent, including live agents and + Dialogflow agents, and a support + customer. Conversations can include + phone calls and text-based chat + sessions. + + """ + # 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 = conversation.GetConversationRequest(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_conversation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def complete_conversation(self, + request: Union[conversation.CompleteConversationRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation.Conversation: + r"""Completes the specified conversation. Finished + conversations are purged from the database after 30 + days. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.CompleteConversationRequest, dict]): + The request object. The request message for + [Conversations.CompleteConversation][google.cloud.dialogflow.v2beta1.Conversations.CompleteConversation]. + name (:class:`str`): + Required. Resource identifier of the conversation to + close. Format: + ``projects//locations//conversations/``. + + 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.dialogflow_v2beta1.types.Conversation: + Represents a conversation. + A conversation is an interaction between + an agent, including live agents and + Dialogflow agents, and a support + customer. Conversations can include + phone calls and text-based chat + sessions. + + """ + # 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 = conversation.CompleteConversationRequest(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.complete_conversation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def batch_create_messages(self, + request: Union[conversation.BatchCreateMessagesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation.BatchCreateMessagesResponse: + r"""Batch ingests messages to conversation. Customers can + use this RPC to ingest historical messages to + conversation. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.BatchCreateMessagesRequest, dict]): + The request object. The request message for + [Conversations.BatchCreateMessagesRequest][]. + parent (:class:`str`): + Required. Resource identifier of the conversation to + create message. Format: + ``projects//locations//conversations/``. + + 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.dialogflow_v2beta1.types.BatchCreateMessagesResponse: + The request message for + [Conversations.BatchCreateMessagesResponse][]. + + """ + # 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 = conversation.BatchCreateMessagesRequest(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.batch_create_messages, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_messages(self, + request: Union[conversation.ListMessagesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListMessagesAsyncPager: + r"""Lists messages that belong to a given conversation. ``messages`` + are ordered by ``create_time`` in descending order. To fetch + updates without duplication, send request with filter + ``create_time_epoch_microseconds > [first item's create_time of previous request]`` + and empty page_token. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListMessagesRequest, dict]): + The request object. The request message for + [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. + parent (:class:`str`): + Required. The name of the conversation to list messages + for. Format: + ``projects//locations//conversations/`` + + 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.dialogflow_v2beta1.services.conversations.pagers.ListMessagesAsyncPager: + The response message for + [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. + + 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 = conversation.ListMessagesRequest(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_messages, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListMessagesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ConversationsAsyncClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/client.py new file mode 100644 index 000000000..9a0e7e653 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/client.py @@ -0,0 +1,926 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2beta1.services.conversations import pagers +from google.cloud.dialogflow_v2beta1.types import conversation +from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation +from google.cloud.dialogflow_v2beta1.types import participant +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ConversationsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ConversationsGrpcTransport +from .transports.grpc_asyncio import ConversationsGrpcAsyncIOTransport + + +class ConversationsClientMeta(type): + """Metaclass for the Conversations 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[ConversationsTransport]] + _transport_registry["grpc"] = ConversationsGrpcTransport + _transport_registry["grpc_asyncio"] = ConversationsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ConversationsTransport]: + """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 ConversationsClient(metaclass=ConversationsClientMeta): + """Service for managing + [Conversations][google.cloud.dialogflow.v2beta1.Conversation]. + """ + + @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 = "dialogflow.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: + ConversationsClient: 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: + ConversationsClient: 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) -> ConversationsTransport: + """Returns the transport used by the client instance. + + Returns: + ConversationsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def conversation_path(project: str,conversation: str,) -> str: + """Returns a fully-qualified conversation string.""" + return "projects/{project}/conversations/{conversation}".format(project=project, conversation=conversation, ) + + @staticmethod + def parse_conversation_path(path: str) -> Dict[str,str]: + """Parses a conversation path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/conversations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def conversation_profile_path(project: str,conversation_profile: str,) -> str: + """Returns a fully-qualified conversation_profile string.""" + return "projects/{project}/conversationProfiles/{conversation_profile}".format(project=project, conversation_profile=conversation_profile, ) + + @staticmethod + def parse_conversation_profile_path(path: str) -> Dict[str,str]: + """Parses a conversation_profile path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/conversationProfiles/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def message_path(project: str,conversation: str,message: str,) -> str: + """Returns a fully-qualified message string.""" + return "projects/{project}/conversations/{conversation}/messages/{message}".format(project=project, conversation=conversation, message=message, ) + + @staticmethod + def parse_message_path(path: str) -> Dict[str,str]: + """Parses a message path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/conversations/(?P.+?)/messages/(?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, ConversationsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the conversations 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, ConversationsTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, ConversationsTransport): + # transport is a ConversationsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def create_conversation(self, + request: Union[gcd_conversation.CreateConversationRequest, dict] = None, + *, + parent: str = None, + conversation: gcd_conversation.Conversation = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_conversation.Conversation: + r"""Creates a new conversation. Conversations are auto-completed + after 24 hours. + + Conversation Lifecycle: There are two stages during a + conversation: Automated Agent Stage and Assist Stage. + + For Automated Agent Stage, there will be a dialogflow agent + responding to user queries. + + For Assist Stage, there's no dialogflow agent responding to user + queries. But we will provide suggestions which are generated + from conversation. + + If + [Conversation.conversation_profile][google.cloud.dialogflow.v2beta1.Conversation.conversation_profile] + is configured for a dialogflow agent, conversation will start + from ``Automated Agent Stage``, otherwise, it will start from + ``Assist Stage``. And during ``Automated Agent Stage``, once an + [Intent][google.cloud.dialogflow.v2beta1.Intent] with + [Intent.live_agent_handoff][google.cloud.dialogflow.v2beta1.Intent.live_agent_handoff] + is triggered, conversation will transfer to Assist Stage. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.CreateConversationRequest, dict]): + The request object. The request message for + [Conversations.CreateConversation][google.cloud.dialogflow.v2beta1.Conversations.CreateConversation]. + parent (str): + Required. Resource identifier of the project creating + the conversation. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + conversation (google.cloud.dialogflow_v2beta1.types.Conversation): + Required. The conversation to create. + This corresponds to the ``conversation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Conversation: + Represents a conversation. + A conversation is an interaction between + an agent, including live agents and + Dialogflow agents, and a support + customer. Conversations can include + phone calls and text-based chat + sessions. + + """ + # 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, conversation]) + if request is 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 gcd_conversation.CreateConversationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_conversation.CreateConversationRequest): + request = gcd_conversation.CreateConversationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if conversation is not None: + request.conversation = conversation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_conversation] + + # Certain 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_conversations(self, + request: Union[conversation.ListConversationsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListConversationsPager: + r"""Returns the list of all conversations in the + specified project. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListConversationsRequest, dict]): + The request object. The request message for + [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. + parent (str): + Required. The project from which to list all + conversation. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.services.conversations.pagers.ListConversationsPager: + The response message for + [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. + + 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 conversation.ListConversationsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversation.ListConversationsRequest): + request = conversation.ListConversationsRequest(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_conversations] + + # Certain 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.ListConversationsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_conversation(self, + request: Union[conversation.GetConversationRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation.Conversation: + r"""Retrieves the specific conversation. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetConversationRequest, dict]): + The request object. The request message for + [Conversations.GetConversation][google.cloud.dialogflow.v2beta1.Conversations.GetConversation]. + name (str): + Required. The name of the conversation. Format: + ``projects//locations//conversations/``. + + 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.dialogflow_v2beta1.types.Conversation: + Represents a conversation. + A conversation is an interaction between + an agent, including live agents and + Dialogflow agents, and a support + customer. Conversations can include + phone calls and text-based chat + sessions. + + """ + # 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 conversation.GetConversationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversation.GetConversationRequest): + request = conversation.GetConversationRequest(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_conversation] + + # Certain 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 complete_conversation(self, + request: Union[conversation.CompleteConversationRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation.Conversation: + r"""Completes the specified conversation. Finished + conversations are purged from the database after 30 + days. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.CompleteConversationRequest, dict]): + The request object. The request message for + [Conversations.CompleteConversation][google.cloud.dialogflow.v2beta1.Conversations.CompleteConversation]. + name (str): + Required. Resource identifier of the conversation to + close. Format: + ``projects//locations//conversations/``. + + 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.dialogflow_v2beta1.types.Conversation: + Represents a conversation. + A conversation is an interaction between + an agent, including live agents and + Dialogflow agents, and a support + customer. Conversations can include + phone calls and text-based chat + sessions. + + """ + # 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 conversation.CompleteConversationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversation.CompleteConversationRequest): + request = conversation.CompleteConversationRequest(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.complete_conversation] + + # Certain 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 batch_create_messages(self, + request: Union[conversation.BatchCreateMessagesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation.BatchCreateMessagesResponse: + r"""Batch ingests messages to conversation. Customers can + use this RPC to ingest historical messages to + conversation. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.BatchCreateMessagesRequest, dict]): + The request object. The request message for + [Conversations.BatchCreateMessagesRequest][]. + parent (str): + Required. Resource identifier of the conversation to + create message. Format: + ``projects//locations//conversations/``. + + 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.dialogflow_v2beta1.types.BatchCreateMessagesResponse: + The request message for + [Conversations.BatchCreateMessagesResponse][]. + + """ + # 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 conversation.BatchCreateMessagesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversation.BatchCreateMessagesRequest): + request = conversation.BatchCreateMessagesRequest(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.batch_create_messages] + + # Certain 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_messages(self, + request: Union[conversation.ListMessagesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListMessagesPager: + r"""Lists messages that belong to a given conversation. ``messages`` + are ordered by ``create_time`` in descending order. To fetch + updates without duplication, send request with filter + ``create_time_epoch_microseconds > [first item's create_time of previous request]`` + and empty page_token. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListMessagesRequest, dict]): + The request object. The request message for + [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. + parent (str): + Required. The name of the conversation to list messages + for. Format: + ``projects//locations//conversations/`` + + 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.dialogflow_v2beta1.services.conversations.pagers.ListMessagesPager: + The response message for + [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. + + 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 conversation.ListMessagesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversation.ListMessagesRequest): + request = conversation.ListMessagesRequest(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_messages] + + # Certain 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.ListMessagesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ConversationsClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/pagers.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/pagers.py new file mode 100644 index 000000000..71670ff6f --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/pagers.py @@ -0,0 +1,263 @@ +# -*- 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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflow_v2beta1.types import conversation +from google.cloud.dialogflow_v2beta1.types import participant + + +class ListConversationsPager: + """A pager for iterating through ``list_conversations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListConversationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``conversations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListConversations`` requests and continue to iterate + through the ``conversations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListConversationsResponse` + 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[..., conversation.ListConversationsResponse], + request: conversation.ListConversationsRequest, + response: conversation.ListConversationsResponse, + *, + 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.dialogflow_v2beta1.types.ListConversationsRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListConversationsResponse): + 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 = conversation.ListConversationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[conversation.ListConversationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[conversation.Conversation]: + for page in self.pages: + yield from page.conversations + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListConversationsAsyncPager: + """A pager for iterating through ``list_conversations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListConversationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``conversations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListConversations`` requests and continue to iterate + through the ``conversations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListConversationsResponse` + 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[conversation.ListConversationsResponse]], + request: conversation.ListConversationsRequest, + response: conversation.ListConversationsResponse, + *, + 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.dialogflow_v2beta1.types.ListConversationsRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListConversationsResponse): + 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 = conversation.ListConversationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[conversation.ListConversationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[conversation.Conversation]: + async def async_generator(): + async for page in self.pages: + for response in page.conversations: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMessagesPager: + """A pager for iterating through ``list_messages`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListMessagesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``messages`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMessages`` requests and continue to iterate + through the ``messages`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListMessagesResponse` + 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[..., conversation.ListMessagesResponse], + request: conversation.ListMessagesRequest, + response: conversation.ListMessagesResponse, + *, + 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.dialogflow_v2beta1.types.ListMessagesRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListMessagesResponse): + 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 = conversation.ListMessagesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[conversation.ListMessagesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[participant.Message]: + for page in self.pages: + yield from page.messages + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMessagesAsyncPager: + """A pager for iterating through ``list_messages`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListMessagesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``messages`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMessages`` requests and continue to iterate + through the ``messages`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListMessagesResponse` + 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[conversation.ListMessagesResponse]], + request: conversation.ListMessagesRequest, + response: conversation.ListMessagesResponse, + *, + 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.dialogflow_v2beta1.types.ListMessagesRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListMessagesResponse): + 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 = conversation.ListMessagesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[conversation.ListMessagesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[participant.Message]: + async def async_generator(): + async for page in self.pages: + for response in page.messages: + 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/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/__init__.py new file mode 100644 index 000000000..9d9ee9030 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/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 ConversationsTransport +from .grpc import ConversationsGrpcTransport +from .grpc_asyncio import ConversationsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ConversationsTransport]] +_transport_registry['grpc'] = ConversationsGrpcTransport +_transport_registry['grpc_asyncio'] = ConversationsGrpcAsyncIOTransport + +__all__ = ( + 'ConversationsTransport', + 'ConversationsGrpcTransport', + 'ConversationsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/base.py new file mode 100644 index 000000000..739bee3a3 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.types import conversation +from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ConversationsTransport(abc.ABC): + """Abstract transport class for Conversations.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_conversation: gapic_v1.method.wrap_method( + self.create_conversation, + default_timeout=None, + client_info=client_info, + ), + self.list_conversations: gapic_v1.method.wrap_method( + self.list_conversations, + default_timeout=None, + client_info=client_info, + ), + self.get_conversation: gapic_v1.method.wrap_method( + self.get_conversation, + default_timeout=None, + client_info=client_info, + ), + self.complete_conversation: gapic_v1.method.wrap_method( + self.complete_conversation, + default_timeout=None, + client_info=client_info, + ), + self.batch_create_messages: gapic_v1.method.wrap_method( + self.batch_create_messages, + default_timeout=None, + client_info=client_info, + ), + self.list_messages: gapic_v1.method.wrap_method( + self.list_messages, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_conversation(self) -> Callable[ + [gcd_conversation.CreateConversationRequest], + Union[ + gcd_conversation.Conversation, + Awaitable[gcd_conversation.Conversation] + ]]: + raise NotImplementedError() + + @property + def list_conversations(self) -> Callable[ + [conversation.ListConversationsRequest], + Union[ + conversation.ListConversationsResponse, + Awaitable[conversation.ListConversationsResponse] + ]]: + raise NotImplementedError() + + @property + def get_conversation(self) -> Callable[ + [conversation.GetConversationRequest], + Union[ + conversation.Conversation, + Awaitable[conversation.Conversation] + ]]: + raise NotImplementedError() + + @property + def complete_conversation(self) -> Callable[ + [conversation.CompleteConversationRequest], + Union[ + conversation.Conversation, + Awaitable[conversation.Conversation] + ]]: + raise NotImplementedError() + + @property + def batch_create_messages(self) -> Callable[ + [conversation.BatchCreateMessagesRequest], + Union[ + conversation.BatchCreateMessagesResponse, + Awaitable[conversation.BatchCreateMessagesResponse] + ]]: + raise NotImplementedError() + + @property + def list_messages(self) -> Callable[ + [conversation.ListMessagesRequest], + Union[ + conversation.ListMessagesResponse, + Awaitable[conversation.ListMessagesResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'ConversationsTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc.py new file mode 100644 index 000000000..6baac5469 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc.py @@ -0,0 +1,415 @@ +# -*- 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 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import conversation +from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation +from .base import ConversationsTransport, DEFAULT_CLIENT_INFO + + +class ConversationsGrpcTransport(ConversationsTransport): + """gRPC backend transport for Conversations. + + Service for managing + [Conversations][google.cloud.dialogflow.v2beta1.Conversation]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 = 'dialogflow.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_conversation(self) -> Callable[ + [gcd_conversation.CreateConversationRequest], + gcd_conversation.Conversation]: + r"""Return a callable for the create conversation method over gRPC. + + Creates a new conversation. Conversations are auto-completed + after 24 hours. + + Conversation Lifecycle: There are two stages during a + conversation: Automated Agent Stage and Assist Stage. + + For Automated Agent Stage, there will be a dialogflow agent + responding to user queries. + + For Assist Stage, there's no dialogflow agent responding to user + queries. But we will provide suggestions which are generated + from conversation. + + If + [Conversation.conversation_profile][google.cloud.dialogflow.v2beta1.Conversation.conversation_profile] + is configured for a dialogflow agent, conversation will start + from ``Automated Agent Stage``, otherwise, it will start from + ``Assist Stage``. And during ``Automated Agent Stage``, once an + [Intent][google.cloud.dialogflow.v2beta1.Intent] with + [Intent.live_agent_handoff][google.cloud.dialogflow.v2beta1.Intent.live_agent_handoff] + is triggered, conversation will transfer to Assist Stage. + + Returns: + Callable[[~.CreateConversationRequest], + ~.Conversation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation' not in self._stubs: + self._stubs['create_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Conversations/CreateConversation', + request_serializer=gcd_conversation.CreateConversationRequest.serialize, + response_deserializer=gcd_conversation.Conversation.deserialize, + ) + return self._stubs['create_conversation'] + + @property + def list_conversations(self) -> Callable[ + [conversation.ListConversationsRequest], + conversation.ListConversationsResponse]: + r"""Return a callable for the list conversations method over gRPC. + + Returns the list of all conversations in the + specified project. + + Returns: + Callable[[~.ListConversationsRequest], + ~.ListConversationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversations' not in self._stubs: + self._stubs['list_conversations'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Conversations/ListConversations', + request_serializer=conversation.ListConversationsRequest.serialize, + response_deserializer=conversation.ListConversationsResponse.deserialize, + ) + return self._stubs['list_conversations'] + + @property + def get_conversation(self) -> Callable[ + [conversation.GetConversationRequest], + conversation.Conversation]: + r"""Return a callable for the get conversation method over gRPC. + + Retrieves the specific conversation. + + Returns: + Callable[[~.GetConversationRequest], + ~.Conversation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation' not in self._stubs: + self._stubs['get_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Conversations/GetConversation', + request_serializer=conversation.GetConversationRequest.serialize, + response_deserializer=conversation.Conversation.deserialize, + ) + return self._stubs['get_conversation'] + + @property + def complete_conversation(self) -> Callable[ + [conversation.CompleteConversationRequest], + conversation.Conversation]: + r"""Return a callable for the complete conversation method over gRPC. + + Completes the specified conversation. Finished + conversations are purged from the database after 30 + days. + + Returns: + Callable[[~.CompleteConversationRequest], + ~.Conversation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_conversation' not in self._stubs: + self._stubs['complete_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Conversations/CompleteConversation', + request_serializer=conversation.CompleteConversationRequest.serialize, + response_deserializer=conversation.Conversation.deserialize, + ) + return self._stubs['complete_conversation'] + + @property + def batch_create_messages(self) -> Callable[ + [conversation.BatchCreateMessagesRequest], + conversation.BatchCreateMessagesResponse]: + r"""Return a callable for the batch create messages method over gRPC. + + Batch ingests messages to conversation. Customers can + use this RPC to ingest historical messages to + conversation. + + Returns: + Callable[[~.BatchCreateMessagesRequest], + ~.BatchCreateMessagesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_create_messages' not in self._stubs: + self._stubs['batch_create_messages'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Conversations/BatchCreateMessages', + request_serializer=conversation.BatchCreateMessagesRequest.serialize, + response_deserializer=conversation.BatchCreateMessagesResponse.deserialize, + ) + return self._stubs['batch_create_messages'] + + @property + def list_messages(self) -> Callable[ + [conversation.ListMessagesRequest], + conversation.ListMessagesResponse]: + r"""Return a callable for the list messages method over gRPC. + + Lists messages that belong to a given conversation. ``messages`` + are ordered by ``create_time`` in descending order. To fetch + updates without duplication, send request with filter + ``create_time_epoch_microseconds > [first item's create_time of previous request]`` + and empty page_token. + + Returns: + Callable[[~.ListMessagesRequest], + ~.ListMessagesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_messages' not in self._stubs: + self._stubs['list_messages'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Conversations/ListMessages', + request_serializer=conversation.ListMessagesRequest.serialize, + response_deserializer=conversation.ListMessagesResponse.deserialize, + ) + return self._stubs['list_messages'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'ConversationsGrpcTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc_asyncio.py new file mode 100644 index 000000000..7cec8f0c2 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc_asyncio.py @@ -0,0 +1,419 @@ +# -*- 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 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import conversation +from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation +from .base import ConversationsTransport, DEFAULT_CLIENT_INFO +from .grpc import ConversationsGrpcTransport + + +class ConversationsGrpcAsyncIOTransport(ConversationsTransport): + """gRPC AsyncIO backend transport for Conversations. + + Service for managing + [Conversations][google.cloud.dialogflow.v2beta1.Conversation]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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_conversation(self) -> Callable[ + [gcd_conversation.CreateConversationRequest], + Awaitable[gcd_conversation.Conversation]]: + r"""Return a callable for the create conversation method over gRPC. + + Creates a new conversation. Conversations are auto-completed + after 24 hours. + + Conversation Lifecycle: There are two stages during a + conversation: Automated Agent Stage and Assist Stage. + + For Automated Agent Stage, there will be a dialogflow agent + responding to user queries. + + For Assist Stage, there's no dialogflow agent responding to user + queries. But we will provide suggestions which are generated + from conversation. + + If + [Conversation.conversation_profile][google.cloud.dialogflow.v2beta1.Conversation.conversation_profile] + is configured for a dialogflow agent, conversation will start + from ``Automated Agent Stage``, otherwise, it will start from + ``Assist Stage``. And during ``Automated Agent Stage``, once an + [Intent][google.cloud.dialogflow.v2beta1.Intent] with + [Intent.live_agent_handoff][google.cloud.dialogflow.v2beta1.Intent.live_agent_handoff] + is triggered, conversation will transfer to Assist Stage. + + Returns: + Callable[[~.CreateConversationRequest], + Awaitable[~.Conversation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation' not in self._stubs: + self._stubs['create_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Conversations/CreateConversation', + request_serializer=gcd_conversation.CreateConversationRequest.serialize, + response_deserializer=gcd_conversation.Conversation.deserialize, + ) + return self._stubs['create_conversation'] + + @property + def list_conversations(self) -> Callable[ + [conversation.ListConversationsRequest], + Awaitable[conversation.ListConversationsResponse]]: + r"""Return a callable for the list conversations method over gRPC. + + Returns the list of all conversations in the + specified project. + + Returns: + Callable[[~.ListConversationsRequest], + Awaitable[~.ListConversationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversations' not in self._stubs: + self._stubs['list_conversations'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Conversations/ListConversations', + request_serializer=conversation.ListConversationsRequest.serialize, + response_deserializer=conversation.ListConversationsResponse.deserialize, + ) + return self._stubs['list_conversations'] + + @property + def get_conversation(self) -> Callable[ + [conversation.GetConversationRequest], + Awaitable[conversation.Conversation]]: + r"""Return a callable for the get conversation method over gRPC. + + Retrieves the specific conversation. + + Returns: + Callable[[~.GetConversationRequest], + Awaitable[~.Conversation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation' not in self._stubs: + self._stubs['get_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Conversations/GetConversation', + request_serializer=conversation.GetConversationRequest.serialize, + response_deserializer=conversation.Conversation.deserialize, + ) + return self._stubs['get_conversation'] + + @property + def complete_conversation(self) -> Callable[ + [conversation.CompleteConversationRequest], + Awaitable[conversation.Conversation]]: + r"""Return a callable for the complete conversation method over gRPC. + + Completes the specified conversation. Finished + conversations are purged from the database after 30 + days. + + Returns: + Callable[[~.CompleteConversationRequest], + Awaitable[~.Conversation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_conversation' not in self._stubs: + self._stubs['complete_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Conversations/CompleteConversation', + request_serializer=conversation.CompleteConversationRequest.serialize, + response_deserializer=conversation.Conversation.deserialize, + ) + return self._stubs['complete_conversation'] + + @property + def batch_create_messages(self) -> Callable[ + [conversation.BatchCreateMessagesRequest], + Awaitable[conversation.BatchCreateMessagesResponse]]: + r"""Return a callable for the batch create messages method over gRPC. + + Batch ingests messages to conversation. Customers can + use this RPC to ingest historical messages to + conversation. + + Returns: + Callable[[~.BatchCreateMessagesRequest], + Awaitable[~.BatchCreateMessagesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_create_messages' not in self._stubs: + self._stubs['batch_create_messages'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Conversations/BatchCreateMessages', + request_serializer=conversation.BatchCreateMessagesRequest.serialize, + response_deserializer=conversation.BatchCreateMessagesResponse.deserialize, + ) + return self._stubs['batch_create_messages'] + + @property + def list_messages(self) -> Callable[ + [conversation.ListMessagesRequest], + Awaitable[conversation.ListMessagesResponse]]: + r"""Return a callable for the list messages method over gRPC. + + Lists messages that belong to a given conversation. ``messages`` + are ordered by ``create_time`` in descending order. To fetch + updates without duplication, send request with filter + ``create_time_epoch_microseconds > [first item's create_time of previous request]`` + and empty page_token. + + Returns: + Callable[[~.ListMessagesRequest], + Awaitable[~.ListMessagesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_messages' not in self._stubs: + self._stubs['list_messages'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Conversations/ListMessages', + request_serializer=conversation.ListMessagesRequest.serialize, + response_deserializer=conversation.ListMessagesResponse.deserialize, + ) + return self._stubs['list_messages'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ConversationsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/__init__.py new file mode 100644 index 000000000..cee70ad81 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/__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 DocumentsClient +from .async_client import DocumentsAsyncClient + +__all__ = ( + 'DocumentsClient', + 'DocumentsAsyncClient', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/async_client.py new file mode 100644 index 000000000..fd3fbc84f --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/async_client.py @@ -0,0 +1,901 @@ +# -*- 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 + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.dialogflow_v2beta1.services.documents import pagers +from google.cloud.dialogflow_v2beta1.types import document +from google.cloud.dialogflow_v2beta1.types import document as gcd_document +from google.cloud.dialogflow_v2beta1.types import gcs +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import DocumentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DocumentsGrpcAsyncIOTransport +from .client import DocumentsClient + + +class DocumentsAsyncClient: + """Service for managing knowledge + [Documents][google.cloud.dialogflow.v2beta1.Document]. + """ + + _client: DocumentsClient + + DEFAULT_ENDPOINT = DocumentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DocumentsClient.DEFAULT_MTLS_ENDPOINT + + document_path = staticmethod(DocumentsClient.document_path) + parse_document_path = staticmethod(DocumentsClient.parse_document_path) + common_billing_account_path = staticmethod(DocumentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DocumentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DocumentsClient.common_folder_path) + parse_common_folder_path = staticmethod(DocumentsClient.parse_common_folder_path) + common_organization_path = staticmethod(DocumentsClient.common_organization_path) + parse_common_organization_path = staticmethod(DocumentsClient.parse_common_organization_path) + common_project_path = staticmethod(DocumentsClient.common_project_path) + parse_common_project_path = staticmethod(DocumentsClient.parse_common_project_path) + common_location_path = staticmethod(DocumentsClient.common_location_path) + parse_common_location_path = staticmethod(DocumentsClient.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: + DocumentsAsyncClient: The constructed client. + """ + return DocumentsClient.from_service_account_info.__func__(DocumentsAsyncClient, 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: + DocumentsAsyncClient: The constructed client. + """ + return DocumentsClient.from_service_account_file.__func__(DocumentsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> DocumentsTransport: + """Returns the transport used by the client instance. + + Returns: + DocumentsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(DocumentsClient).get_transport_class, type(DocumentsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, DocumentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the documents 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, ~.DocumentsTransport]): 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 = DocumentsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_documents(self, + request: Union[document.ListDocumentsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDocumentsAsyncPager: + r"""Returns the list of all documents of the knowledge base. + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListDocumentsRequest, dict]): + The request object. Request message for + [Documents.ListDocuments][google.cloud.dialogflow.v2beta1.Documents.ListDocuments]. + parent (:class:`str`): + Required. The knowledge base to list all documents for. + Format: + ``projects//locations//knowledgeBases/``. + + 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.dialogflow_v2beta1.services.documents.pagers.ListDocumentsAsyncPager: + Response message for + [Documents.ListDocuments][google.cloud.dialogflow.v2beta1.Documents.ListDocuments]. + + 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 = document.ListDocumentsRequest(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_documents, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDocumentsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_document(self, + request: Union[document.GetDocumentRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document.Document: + r"""Retrieves the specified document. + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetDocumentRequest, dict]): + The request object. Request message for + [Documents.GetDocument][google.cloud.dialogflow.v2beta1.Documents.GetDocument]. + name (:class:`str`): + Required. The name of the document to retrieve. Format + ``projects//locations//knowledgeBases//documents/``. + + 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.dialogflow_v2beta1.types.Document: + A knowledge document to be used by a + [KnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBase]. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases.documents + resource is deprecated; only use + projects.knowledgeBases.documents. + + """ + # 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 = document.GetDocumentRequest(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_document, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_document(self, + request: Union[gcd_document.CreateDocumentRequest, dict] = None, + *, + parent: str = None, + document: gcd_document.Document = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new document. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] + - ``response``: + [Document][google.cloud.dialogflow.v2beta1.Document] + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.CreateDocumentRequest, dict]): + The request object. Request message for + [Documents.CreateDocument][google.cloud.dialogflow.v2beta1.Documents.CreateDocument]. + parent (:class:`str`): + Required. The knowledge base to create a document for. + Format: + ``projects//locations//knowledgeBases/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + document (:class:`google.cloud.dialogflow_v2beta1.types.Document`): + Required. The document to create. + This corresponds to the ``document`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.dialogflow_v2beta1.types.Document` + A knowledge document to be used by a + [KnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBase]. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases.documents + resource is deprecated; only use + projects.knowledgeBases.documents. + + """ + # 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, document]) + if request is 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 = gcd_document.CreateDocumentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if document is not None: + request.document = document + + # 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_document, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcd_document.Document, + metadata_type=gcd_document.KnowledgeOperationMetadata, + ) + + # Done; return the response. + return response + + async def import_documents(self, + request: Union[document.ImportDocumentsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Create documents by importing data from external sources. + Dialogflow supports up to 350 documents in each request. If you + try to import more, Dialogflow will return an error. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] + - ``response``: + [ImportDocumentsResponse][google.cloud.dialogflow.v2beta1.ImportDocumentsResponse] + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ImportDocumentsRequest, dict]): + The request object. Request message for + [Documents.ImportDocuments][google.cloud.dialogflow.v2beta1.Documents.ImportDocuments]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.dialogflow_v2beta1.types.ImportDocumentsResponse` + Response message for + [Documents.ImportDocuments][google.cloud.dialogflow.v2beta1.Documents.ImportDocuments]. + + """ + # Create or coerce a protobuf request object. + request = document.ImportDocumentsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_documents, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + document.ImportDocumentsResponse, + metadata_type=document.KnowledgeOperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_document(self, + request: Union[document.DeleteDocumentRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes the specified document. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] + - ``response``: An `Empty + message `__ + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.DeleteDocumentRequest, dict]): + The request object. Request message for + [Documents.DeleteDocument][google.cloud.dialogflow.v2beta1.Documents.DeleteDocument]. + name (:class:`str`): + Required. The name of the document to delete. Format: + ``projects//locations//knowledgeBases//documents/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = document.DeleteDocumentRequest(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_document, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=document.KnowledgeOperationMetadata, + ) + + # Done; return the response. + return response + + async def update_document(self, + request: Union[gcd_document.UpdateDocumentRequest, dict] = None, + *, + document: gcd_document.Document = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the specified document. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] + - ``response``: + [Document][google.cloud.dialogflow.v2beta1.Document] + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.UpdateDocumentRequest, dict]): + The request object. Request message for + [Documents.UpdateDocument][google.cloud.dialogflow.v2beta1.Documents.UpdateDocument]. + document (:class:`google.cloud.dialogflow_v2beta1.types.Document`): + Required. The document to update. + This corresponds to the ``document`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Not specified means ``update all``. Currently, + only ``display_name`` can be updated, an InvalidArgument + will be returned for attempting to update other 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflow_v2beta1.types.Document` + A knowledge document to be used by a + [KnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBase]. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases.documents + resource is deprecated; only use + projects.knowledgeBases.documents. + + """ + # 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([document, 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 = gcd_document.UpdateDocumentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if document is not None: + request.document = document + 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_document, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("document.name", request.document.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcd_document.Document, + metadata_type=gcd_document.KnowledgeOperationMetadata, + ) + + # Done; return the response. + return response + + async def reload_document(self, + request: Union[document.ReloadDocumentRequest, dict] = None, + *, + name: str = None, + gcs_source: gcs.GcsSource = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Reloads the specified document from its specified source, + content_uri or content. The previously loaded content of the + document will be deleted. Note: Even when the content of the + document has not changed, there still may be side effects + because of internal implementation changes. Note: If the + document source is Google Cloud Storage URI, its metadata will + be replaced with the custom metadata from Google Cloud Storage + if the ``import_gcs_custom_metadata`` field is set to true in + the request. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] + - ``response``: + [Document][google.cloud.dialogflow.v2beta1.Document] + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ReloadDocumentRequest, dict]): + The request object. Request message for + [Documents.ReloadDocument][google.cloud.dialogflow.v2beta1.Documents.ReloadDocument]. + name (:class:`str`): + Required. The name of the document to reload. Format: + ``projects//locations//knowledgeBases//documents/`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + gcs_source (:class:`google.cloud.dialogflow_v2beta1.types.GcsSource`): + The path for a Cloud Storage source + file for reloading document content. If + not provided, the Document's existing + source will be reloaded. + + This corresponds to the ``gcs_source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflow_v2beta1.types.Document` + A knowledge document to be used by a + [KnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBase]. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases.documents + resource is deprecated; only use + projects.knowledgeBases.documents. + + """ + # 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, gcs_source]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = document.ReloadDocumentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if gcs_source is not None: + request.gcs_source = gcs_source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.reload_document, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + document.Document, + metadata_type=document.KnowledgeOperationMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "DocumentsAsyncClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/client.py new file mode 100644 index 000000000..e12bfeb3a --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/client.py @@ -0,0 +1,1100 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.dialogflow_v2beta1.services.documents import pagers +from google.cloud.dialogflow_v2beta1.types import document +from google.cloud.dialogflow_v2beta1.types import document as gcd_document +from google.cloud.dialogflow_v2beta1.types import gcs +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import DocumentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DocumentsGrpcTransport +from .transports.grpc_asyncio import DocumentsGrpcAsyncIOTransport + + +class DocumentsClientMeta(type): + """Metaclass for the Documents 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[DocumentsTransport]] + _transport_registry["grpc"] = DocumentsGrpcTransport + _transport_registry["grpc_asyncio"] = DocumentsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[DocumentsTransport]: + """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 DocumentsClient(metaclass=DocumentsClientMeta): + """Service for managing knowledge + [Documents][google.cloud.dialogflow.v2beta1.Document]. + """ + + @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 = "dialogflow.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: + DocumentsClient: 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: + DocumentsClient: 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) -> DocumentsTransport: + """Returns the transport used by the client instance. + + Returns: + DocumentsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def document_path(project: str,knowledge_base: str,document: str,) -> str: + """Returns a fully-qualified document string.""" + return "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format(project=project, knowledge_base=knowledge_base, document=document, ) + + @staticmethod + def parse_document_path(path: str) -> Dict[str,str]: + """Parses a document path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/knowledgeBases/(?P.+?)/documents/(?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, DocumentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the documents 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, DocumentsTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, DocumentsTransport): + # transport is a DocumentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_documents(self, + request: Union[document.ListDocumentsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDocumentsPager: + r"""Returns the list of all documents of the knowledge base. + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListDocumentsRequest, dict]): + The request object. Request message for + [Documents.ListDocuments][google.cloud.dialogflow.v2beta1.Documents.ListDocuments]. + parent (str): + Required. The knowledge base to list all documents for. + Format: + ``projects//locations//knowledgeBases/``. + + 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.dialogflow_v2beta1.services.documents.pagers.ListDocumentsPager: + Response message for + [Documents.ListDocuments][google.cloud.dialogflow.v2beta1.Documents.ListDocuments]. + + 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 document.ListDocumentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document.ListDocumentsRequest): + request = document.ListDocumentsRequest(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_documents] + + # Certain 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.ListDocumentsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_document(self, + request: Union[document.GetDocumentRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document.Document: + r"""Retrieves the specified document. + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetDocumentRequest, dict]): + The request object. Request message for + [Documents.GetDocument][google.cloud.dialogflow.v2beta1.Documents.GetDocument]. + name (str): + Required. The name of the document to retrieve. Format + ``projects//locations//knowledgeBases//documents/``. + + 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.dialogflow_v2beta1.types.Document: + A knowledge document to be used by a + [KnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBase]. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases.documents + resource is deprecated; only use + projects.knowledgeBases.documents. + + """ + # 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 document.GetDocumentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document.GetDocumentRequest): + request = document.GetDocumentRequest(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_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_document(self, + request: Union[gcd_document.CreateDocumentRequest, dict] = None, + *, + parent: str = None, + document: gcd_document.Document = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new document. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] + - ``response``: + [Document][google.cloud.dialogflow.v2beta1.Document] + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.CreateDocumentRequest, dict]): + The request object. Request message for + [Documents.CreateDocument][google.cloud.dialogflow.v2beta1.Documents.CreateDocument]. + parent (str): + Required. The knowledge base to create a document for. + Format: + ``projects//locations//knowledgeBases/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + document (google.cloud.dialogflow_v2beta1.types.Document): + Required. The document to create. + This corresponds to the ``document`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.dialogflow_v2beta1.types.Document` + A knowledge document to be used by a + [KnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBase]. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases.documents + resource is deprecated; only use + projects.knowledgeBases.documents. + + """ + # 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, document]) + if request is 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 gcd_document.CreateDocumentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_document.CreateDocumentRequest): + request = gcd_document.CreateDocumentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if document is not None: + request.document = document + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_document] + + # Certain 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, + gcd_document.Document, + metadata_type=gcd_document.KnowledgeOperationMetadata, + ) + + # Done; return the response. + return response + + def import_documents(self, + request: Union[document.ImportDocumentsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Create documents by importing data from external sources. + Dialogflow supports up to 350 documents in each request. If you + try to import more, Dialogflow will return an error. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] + - ``response``: + [ImportDocumentsResponse][google.cloud.dialogflow.v2beta1.ImportDocumentsResponse] + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ImportDocumentsRequest, dict]): + The request object. Request message for + [Documents.ImportDocuments][google.cloud.dialogflow.v2beta1.Documents.ImportDocuments]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.dialogflow_v2beta1.types.ImportDocumentsResponse` + Response message for + [Documents.ImportDocuments][google.cloud.dialogflow.v2beta1.Documents.ImportDocuments]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a document.ImportDocumentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document.ImportDocumentsRequest): + request = document.ImportDocumentsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_documents] + + # Certain 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, + document.ImportDocumentsResponse, + metadata_type=document.KnowledgeOperationMetadata, + ) + + # Done; return the response. + return response + + def delete_document(self, + request: Union[document.DeleteDocumentRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes the specified document. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] + - ``response``: An `Empty + message `__ + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.DeleteDocumentRequest, dict]): + The request object. Request message for + [Documents.DeleteDocument][google.cloud.dialogflow.v2beta1.Documents.DeleteDocument]. + name (str): + Required. The name of the document to delete. Format: + ``projects//locations//knowledgeBases//documents/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a document.DeleteDocumentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document.DeleteDocumentRequest): + request = document.DeleteDocumentRequest(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_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=document.KnowledgeOperationMetadata, + ) + + # Done; return the response. + return response + + def update_document(self, + request: Union[gcd_document.UpdateDocumentRequest, dict] = None, + *, + document: gcd_document.Document = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the specified document. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] + - ``response``: + [Document][google.cloud.dialogflow.v2beta1.Document] + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.UpdateDocumentRequest, dict]): + The request object. Request message for + [Documents.UpdateDocument][google.cloud.dialogflow.v2beta1.Documents.UpdateDocument]. + document (google.cloud.dialogflow_v2beta1.types.Document): + Required. The document to update. + This corresponds to the ``document`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Not specified means ``update all``. Currently, + only ``display_name`` can be updated, an InvalidArgument + will be returned for attempting to update other 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflow_v2beta1.types.Document` + A knowledge document to be used by a + [KnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBase]. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases.documents + resource is deprecated; only use + projects.knowledgeBases.documents. + + """ + # 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([document, 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 gcd_document.UpdateDocumentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_document.UpdateDocumentRequest): + request = gcd_document.UpdateDocumentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if document is not None: + request.document = document + 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_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("document.name", request.document.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcd_document.Document, + metadata_type=gcd_document.KnowledgeOperationMetadata, + ) + + # Done; return the response. + return response + + def reload_document(self, + request: Union[document.ReloadDocumentRequest, dict] = None, + *, + name: str = None, + gcs_source: gcs.GcsSource = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Reloads the specified document from its specified source, + content_uri or content. The previously loaded content of the + document will be deleted. Note: Even when the content of the + document has not changed, there still may be side effects + because of internal implementation changes. Note: If the + document source is Google Cloud Storage URI, its metadata will + be replaced with the custom metadata from Google Cloud Storage + if the ``import_gcs_custom_metadata`` field is set to true in + the request. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] + - ``response``: + [Document][google.cloud.dialogflow.v2beta1.Document] + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ReloadDocumentRequest, dict]): + The request object. Request message for + [Documents.ReloadDocument][google.cloud.dialogflow.v2beta1.Documents.ReloadDocument]. + name (str): + Required. The name of the document to reload. Format: + ``projects//locations//knowledgeBases//documents/`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + gcs_source (google.cloud.dialogflow_v2beta1.types.GcsSource): + The path for a Cloud Storage source + file for reloading document content. If + not provided, the Document's existing + source will be reloaded. + + This corresponds to the ``gcs_source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflow_v2beta1.types.Document` + A knowledge document to be used by a + [KnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBase]. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases.documents + resource is deprecated; only use + projects.knowledgeBases.documents. + + """ + # 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, gcs_source]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a document.ReloadDocumentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document.ReloadDocumentRequest): + request = document.ReloadDocumentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if gcs_source is not None: + request.gcs_source = gcs_source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.reload_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + document.Document, + metadata_type=document.KnowledgeOperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "DocumentsClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/pagers.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/pagers.py new file mode 100644 index 000000000..eb9b17509 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflow_v2beta1.types import document + + +class ListDocumentsPager: + """A pager for iterating through ``list_documents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListDocumentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``documents`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDocuments`` requests and continue to iterate + through the ``documents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListDocumentsResponse` + 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[..., document.ListDocumentsResponse], + request: document.ListDocumentsRequest, + response: document.ListDocumentsResponse, + *, + 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.dialogflow_v2beta1.types.ListDocumentsRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListDocumentsResponse): + 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 = document.ListDocumentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[document.ListDocumentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[document.Document]: + for page in self.pages: + yield from page.documents + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDocumentsAsyncPager: + """A pager for iterating through ``list_documents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListDocumentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``documents`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDocuments`` requests and continue to iterate + through the ``documents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListDocumentsResponse` + 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[document.ListDocumentsResponse]], + request: document.ListDocumentsRequest, + response: document.ListDocumentsResponse, + *, + 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.dialogflow_v2beta1.types.ListDocumentsRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListDocumentsResponse): + 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 = document.ListDocumentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[document.ListDocumentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[document.Document]: + async def async_generator(): + async for page in self.pages: + for response in page.documents: + 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/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/__init__.py new file mode 100644 index 000000000..f9ae67be5 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/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 DocumentsTransport +from .grpc import DocumentsGrpcTransport +from .grpc_asyncio import DocumentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DocumentsTransport]] +_transport_registry['grpc'] = DocumentsGrpcTransport +_transport_registry['grpc_asyncio'] = DocumentsGrpcAsyncIOTransport + +__all__ = ( + 'DocumentsTransport', + 'DocumentsGrpcTransport', + 'DocumentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/base.py new file mode 100644 index 000000000..df1c3670d --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/base.py @@ -0,0 +1,239 @@ +# -*- 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.types import document +from google.cloud.dialogflow_v2beta1.types import document as gcd_document +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-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class DocumentsTransport(abc.ABC): + """Abstract transport class for Documents.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_documents: gapic_v1.method.wrap_method( + self.list_documents, + default_timeout=None, + client_info=client_info, + ), + self.get_document: gapic_v1.method.wrap_method( + self.get_document, + default_timeout=None, + client_info=client_info, + ), + self.create_document: gapic_v1.method.wrap_method( + self.create_document, + default_timeout=None, + client_info=client_info, + ), + self.import_documents: gapic_v1.method.wrap_method( + self.import_documents, + default_timeout=None, + client_info=client_info, + ), + self.delete_document: gapic_v1.method.wrap_method( + self.delete_document, + default_timeout=None, + client_info=client_info, + ), + self.update_document: gapic_v1.method.wrap_method( + self.update_document, + default_timeout=None, + client_info=client_info, + ), + self.reload_document: gapic_v1.method.wrap_method( + self.reload_document, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_documents(self) -> Callable[ + [document.ListDocumentsRequest], + Union[ + document.ListDocumentsResponse, + Awaitable[document.ListDocumentsResponse] + ]]: + raise NotImplementedError() + + @property + def get_document(self) -> Callable[ + [document.GetDocumentRequest], + Union[ + document.Document, + Awaitable[document.Document] + ]]: + raise NotImplementedError() + + @property + def create_document(self) -> Callable[ + [gcd_document.CreateDocumentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def import_documents(self) -> Callable[ + [document.ImportDocumentsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_document(self) -> Callable[ + [document.DeleteDocumentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_document(self) -> Callable[ + [gcd_document.UpdateDocumentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def reload_document(self) -> Callable[ + [document.ReloadDocumentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'DocumentsTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc.py new file mode 100644 index 000000000..447017f11 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc.py @@ -0,0 +1,509 @@ +# -*- 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 +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import document +from google.cloud.dialogflow_v2beta1.types import document as gcd_document +from google.longrunning import operations_pb2 # type: ignore +from .base import DocumentsTransport, DEFAULT_CLIENT_INFO + + +class DocumentsGrpcTransport(DocumentsTransport): + """gRPC backend transport for Documents. + + Service for managing knowledge + [Documents][google.cloud.dialogflow.v2beta1.Document]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 = 'dialogflow.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 list_documents(self) -> Callable[ + [document.ListDocumentsRequest], + document.ListDocumentsResponse]: + r"""Return a callable for the list documents method over gRPC. + + Returns the list of all documents of the knowledge base. + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Returns: + Callable[[~.ListDocumentsRequest], + ~.ListDocumentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_documents' not in self._stubs: + self._stubs['list_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Documents/ListDocuments', + request_serializer=document.ListDocumentsRequest.serialize, + response_deserializer=document.ListDocumentsResponse.deserialize, + ) + return self._stubs['list_documents'] + + @property + def get_document(self) -> Callable[ + [document.GetDocumentRequest], + document.Document]: + r"""Return a callable for the get document method over gRPC. + + Retrieves the specified document. + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Returns: + Callable[[~.GetDocumentRequest], + ~.Document]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['get_document'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Documents/GetDocument', + request_serializer=document.GetDocumentRequest.serialize, + response_deserializer=document.Document.deserialize, + ) + return self._stubs['get_document'] + + @property + def create_document(self) -> Callable[ + [gcd_document.CreateDocumentRequest], + operations_pb2.Operation]: + r"""Return a callable for the create document method over gRPC. + + Creates a new document. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] + - ``response``: + [Document][google.cloud.dialogflow.v2beta1.Document] + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Returns: + Callable[[~.CreateDocumentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['create_document'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Documents/CreateDocument', + request_serializer=gcd_document.CreateDocumentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_document'] + + @property + def import_documents(self) -> Callable[ + [document.ImportDocumentsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import documents method over gRPC. + + Create documents by importing data from external sources. + Dialogflow supports up to 350 documents in each request. If you + try to import more, Dialogflow will return an error. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] + - ``response``: + [ImportDocumentsResponse][google.cloud.dialogflow.v2beta1.ImportDocumentsResponse] + + Returns: + Callable[[~.ImportDocumentsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_documents' not in self._stubs: + self._stubs['import_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Documents/ImportDocuments', + request_serializer=document.ImportDocumentsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_documents'] + + @property + def delete_document(self) -> Callable[ + [document.DeleteDocumentRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete document method over gRPC. + + Deletes the specified document. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] + - ``response``: An `Empty + message `__ + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Returns: + Callable[[~.DeleteDocumentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['delete_document'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Documents/DeleteDocument', + request_serializer=document.DeleteDocumentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_document'] + + @property + def update_document(self) -> Callable[ + [gcd_document.UpdateDocumentRequest], + operations_pb2.Operation]: + r"""Return a callable for the update document method over gRPC. + + Updates the specified document. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] + - ``response``: + [Document][google.cloud.dialogflow.v2beta1.Document] + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Returns: + Callable[[~.UpdateDocumentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['update_document'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Documents/UpdateDocument', + request_serializer=gcd_document.UpdateDocumentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_document'] + + @property + def reload_document(self) -> Callable[ + [document.ReloadDocumentRequest], + operations_pb2.Operation]: + r"""Return a callable for the reload document method over gRPC. + + Reloads the specified document from its specified source, + content_uri or content. The previously loaded content of the + document will be deleted. Note: Even when the content of the + document has not changed, there still may be side effects + because of internal implementation changes. Note: If the + document source is Google Cloud Storage URI, its metadata will + be replaced with the custom metadata from Google Cloud Storage + if the ``import_gcs_custom_metadata`` field is set to true in + the request. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] + - ``response``: + [Document][google.cloud.dialogflow.v2beta1.Document] + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Returns: + Callable[[~.ReloadDocumentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'reload_document' not in self._stubs: + self._stubs['reload_document'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Documents/ReloadDocument', + request_serializer=document.ReloadDocumentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['reload_document'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'DocumentsGrpcTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc_asyncio.py new file mode 100644 index 000000000..15d86f30e --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc_asyncio.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 warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import document +from google.cloud.dialogflow_v2beta1.types import document as gcd_document +from google.longrunning import operations_pb2 # type: ignore +from .base import DocumentsTransport, DEFAULT_CLIENT_INFO +from .grpc import DocumentsGrpcTransport + + +class DocumentsGrpcAsyncIOTransport(DocumentsTransport): + """gRPC AsyncIO backend transport for Documents. + + Service for managing knowledge + [Documents][google.cloud.dialogflow.v2beta1.Document]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 list_documents(self) -> Callable[ + [document.ListDocumentsRequest], + Awaitable[document.ListDocumentsResponse]]: + r"""Return a callable for the list documents method over gRPC. + + Returns the list of all documents of the knowledge base. + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Returns: + Callable[[~.ListDocumentsRequest], + Awaitable[~.ListDocumentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_documents' not in self._stubs: + self._stubs['list_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Documents/ListDocuments', + request_serializer=document.ListDocumentsRequest.serialize, + response_deserializer=document.ListDocumentsResponse.deserialize, + ) + return self._stubs['list_documents'] + + @property + def get_document(self) -> Callable[ + [document.GetDocumentRequest], + Awaitable[document.Document]]: + r"""Return a callable for the get document method over gRPC. + + Retrieves the specified document. + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Returns: + Callable[[~.GetDocumentRequest], + Awaitable[~.Document]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['get_document'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Documents/GetDocument', + request_serializer=document.GetDocumentRequest.serialize, + response_deserializer=document.Document.deserialize, + ) + return self._stubs['get_document'] + + @property + def create_document(self) -> Callable[ + [gcd_document.CreateDocumentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create document method over gRPC. + + Creates a new document. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] + - ``response``: + [Document][google.cloud.dialogflow.v2beta1.Document] + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Returns: + Callable[[~.CreateDocumentRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_document' not in self._stubs: + self._stubs['create_document'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Documents/CreateDocument', + request_serializer=gcd_document.CreateDocumentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_document'] + + @property + def import_documents(self) -> Callable[ + [document.ImportDocumentsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import documents method over gRPC. + + Create documents by importing data from external sources. + Dialogflow supports up to 350 documents in each request. If you + try to import more, Dialogflow will return an error. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] + - ``response``: + [ImportDocumentsResponse][google.cloud.dialogflow.v2beta1.ImportDocumentsResponse] + + Returns: + Callable[[~.ImportDocumentsRequest], + 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_documents' not in self._stubs: + self._stubs['import_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Documents/ImportDocuments', + request_serializer=document.ImportDocumentsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_documents'] + + @property + def delete_document(self) -> Callable[ + [document.DeleteDocumentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete document method over gRPC. + + Deletes the specified document. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] + - ``response``: An `Empty + message `__ + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Returns: + Callable[[~.DeleteDocumentRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_document' not in self._stubs: + self._stubs['delete_document'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Documents/DeleteDocument', + request_serializer=document.DeleteDocumentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_document'] + + @property + def update_document(self) -> Callable[ + [gcd_document.UpdateDocumentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update document method over gRPC. + + Updates the specified document. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] + - ``response``: + [Document][google.cloud.dialogflow.v2beta1.Document] + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Returns: + Callable[[~.UpdateDocumentRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_document' not in self._stubs: + self._stubs['update_document'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Documents/UpdateDocument', + request_serializer=gcd_document.UpdateDocumentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_document'] + + @property + def reload_document(self) -> Callable[ + [document.ReloadDocumentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the reload document method over gRPC. + + Reloads the specified document from its specified source, + content_uri or content. The previously loaded content of the + document will be deleted. Note: Even when the content of the + document has not changed, there still may be side effects + because of internal implementation changes. Note: If the + document source is Google Cloud Storage URI, its metadata will + be replaced with the custom metadata from Google Cloud Storage + if the ``import_gcs_custom_metadata`` field is set to true in + the request. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] + - ``response``: + [Document][google.cloud.dialogflow.v2beta1.Document] + + Note: The ``projects.agent.knowledgeBases.documents`` resource + is deprecated; only use ``projects.knowledgeBases.documents``. + + Returns: + Callable[[~.ReloadDocumentRequest], + 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 'reload_document' not in self._stubs: + self._stubs['reload_document'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Documents/ReloadDocument', + request_serializer=document.ReloadDocumentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['reload_document'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'DocumentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/__init__.py new file mode 100644 index 000000000..82dfe86fd --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/__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 EntityTypesClient +from .async_client import EntityTypesAsyncClient + +__all__ = ( + 'EntityTypesClient', + 'EntityTypesAsyncClient', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/async_client.py new file mode 100644 index 000000000..bce60357f --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/async_client.py @@ -0,0 +1,1301 @@ +# -*- 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 + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.dialogflow_v2beta1.services.entity_types import pagers +from google.cloud.dialogflow_v2beta1.types import entity_type +from google.cloud.dialogflow_v2beta1.types import entity_type as gcd_entity_type +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import EntityTypesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import EntityTypesGrpcAsyncIOTransport +from .client import EntityTypesClient + + +class EntityTypesAsyncClient: + """Service for managing + [EntityTypes][google.cloud.dialogflow.v2beta1.EntityType]. + """ + + _client: EntityTypesClient + + DEFAULT_ENDPOINT = EntityTypesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = EntityTypesClient.DEFAULT_MTLS_ENDPOINT + + entity_type_path = staticmethod(EntityTypesClient.entity_type_path) + parse_entity_type_path = staticmethod(EntityTypesClient.parse_entity_type_path) + common_billing_account_path = staticmethod(EntityTypesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(EntityTypesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(EntityTypesClient.common_folder_path) + parse_common_folder_path = staticmethod(EntityTypesClient.parse_common_folder_path) + common_organization_path = staticmethod(EntityTypesClient.common_organization_path) + parse_common_organization_path = staticmethod(EntityTypesClient.parse_common_organization_path) + common_project_path = staticmethod(EntityTypesClient.common_project_path) + parse_common_project_path = staticmethod(EntityTypesClient.parse_common_project_path) + common_location_path = staticmethod(EntityTypesClient.common_location_path) + parse_common_location_path = staticmethod(EntityTypesClient.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: + EntityTypesAsyncClient: The constructed client. + """ + return EntityTypesClient.from_service_account_info.__func__(EntityTypesAsyncClient, 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: + EntityTypesAsyncClient: The constructed client. + """ + return EntityTypesClient.from_service_account_file.__func__(EntityTypesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> EntityTypesTransport: + """Returns the transport used by the client instance. + + Returns: + EntityTypesTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(EntityTypesClient).get_transport_class, type(EntityTypesClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, EntityTypesTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the entity types 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, ~.EntityTypesTransport]): 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 = EntityTypesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_entity_types(self, + request: Union[entity_type.ListEntityTypesRequest, dict] = None, + *, + parent: str = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEntityTypesAsyncPager: + r"""Returns the list of all entity types in the specified + agent. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListEntityTypesRequest, dict]): + The request object. The request message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.ListEntityTypes]. + parent (:class:`str`): + Required. The agent to list all entity types from. + Supported formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (:class:`str`): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.services.entity_types.pagers.ListEntityTypesAsyncPager: + The response message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.ListEntityTypes]. + + 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, language_code]) + if request is 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 = entity_type.ListEntityTypesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if language_code is not None: + request.language_code = language_code + + # 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_entity_types, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEntityTypesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_entity_type(self, + request: Union[entity_type.GetEntityTypeRequest, dict] = None, + *, + name: str = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> entity_type.EntityType: + r"""Retrieves the specified entity type. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetEntityTypeRequest, dict]): + The request object. The request message for + [EntityTypes.GetEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.GetEntityType]. + name (:class:`str`): + Required. The name of the entity type. Supported + formats: + + - ``projects//agent/entityTypes/`` + - ``projects//locations//agent/entityTypes/`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (:class:`str`): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.EntityType: + Each intent parameter has a type, called the entity type, which dictates + exactly how data from an end-user expression is + extracted. + + Dialogflow provides predefined system entities that + can match many common types of data. For example, + there are system entities for matching dates, times, + colors, email addresses, and so on. You can also + create your own custom entities for matching custom + data. For example, you could define a vegetable + entity that can match the types of vegetables + available for purchase with a grocery store agent. + + For more information, see the [Entity + guide](\ https://cloud.google.com/dialogflow/docs/entities-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, language_code]) + if request is 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 = entity_type.GetEntityTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if language_code is not None: + request.language_code = language_code + + # 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_entity_type, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_entity_type(self, + request: Union[gcd_entity_type.CreateEntityTypeRequest, dict] = None, + *, + parent: str = None, + entity_type: gcd_entity_type.EntityType = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_entity_type.EntityType: + r"""Creates an entity type in the specified agent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.CreateEntityTypeRequest, dict]): + The request object. The request message for + [EntityTypes.CreateEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.CreateEntityType]. + parent (:class:`str`): + Required. The agent to create a entity type for. + Supported formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entity_type (:class:`google.cloud.dialogflow_v2beta1.types.EntityType`): + Required. The entity type to create. + This corresponds to the ``entity_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (:class:`str`): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.EntityType: + Each intent parameter has a type, called the entity type, which dictates + exactly how data from an end-user expression is + extracted. + + Dialogflow provides predefined system entities that + can match many common types of data. For example, + there are system entities for matching dates, times, + colors, email addresses, and so on. You can also + create your own custom entities for matching custom + data. For example, you could define a vegetable + entity that can match the types of vegetables + available for purchase with a grocery store agent. + + For more information, see the [Entity + guide](\ https://cloud.google.com/dialogflow/docs/entities-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, entity_type, language_code]) + if request is 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 = gcd_entity_type.CreateEntityTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entity_type is not None: + request.entity_type = entity_type + if language_code is not None: + request.language_code = language_code + + # 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_entity_type, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_entity_type(self, + request: Union[gcd_entity_type.UpdateEntityTypeRequest, dict] = None, + *, + entity_type: gcd_entity_type.EntityType = None, + language_code: str = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_entity_type.EntityType: + r"""Updates the specified entity type. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.UpdateEntityTypeRequest, dict]): + The request object. The request message for + [EntityTypes.UpdateEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.UpdateEntityType]. + entity_type (:class:`google.cloud.dialogflow_v2beta1.types.EntityType`): + Required. The entity type to update. + This corresponds to the ``entity_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (:class:`str`): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.EntityType: + Each intent parameter has a type, called the entity type, which dictates + exactly how data from an end-user expression is + extracted. + + Dialogflow provides predefined system entities that + can match many common types of data. For example, + there are system entities for matching dates, times, + colors, email addresses, and so on. You can also + create your own custom entities for matching custom + data. For example, you could define a vegetable + entity that can match the types of vegetables + available for purchase with a grocery store agent. + + For more information, see the [Entity + guide](\ https://cloud.google.com/dialogflow/docs/entities-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([entity_type, language_code, 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 = gcd_entity_type.UpdateEntityTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if entity_type is not None: + request.entity_type = entity_type + if language_code is not None: + request.language_code = language_code + 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_entity_type, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("entity_type.name", request.entity_type.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_entity_type(self, + request: Union[entity_type.DeleteEntityTypeRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified entity type. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.DeleteEntityTypeRequest, dict]): + The request object. The request message for + [EntityTypes.DeleteEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.DeleteEntityType]. + name (:class:`str`): + Required. The name of the entity type to delete. + Supported formats: + + - ``projects//agent/entityTypes/`` + - ``projects//locations//agent/entityTypes/`` + + 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 = entity_type.DeleteEntityTypeRequest(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_entity_type, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def batch_update_entity_types(self, + request: Union[entity_type.BatchUpdateEntityTypesRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates/Creates multiple entity types in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [BatchUpdateEntityTypesResponse][google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse] + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.BatchUpdateEntityTypesRequest, dict]): + The request object. The request message for + [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.dialogflow_v2beta1.types.BatchUpdateEntityTypesResponse` + The response message for + [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes]. + + """ + # Create or coerce a protobuf request object. + request = entity_type.BatchUpdateEntityTypesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_update_entity_types, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + entity_type.BatchUpdateEntityTypesResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def batch_delete_entity_types(self, + request: Union[entity_type.BatchDeleteEntityTypesRequest, dict] = None, + *, + parent: str = None, + entity_type_names: Sequence[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes entity types in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.BatchDeleteEntityTypesRequest, dict]): + The request object. The request message for + [EntityTypes.BatchDeleteEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchDeleteEntityTypes]. + parent (:class:`str`): + Required. The name of the agent to delete all entities + types for. Supported formats: + + - ``projects//agent``, + - ``projects//locations//agent``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entity_type_names (:class:`Sequence[str]`): + Required. The names entity types to delete. All names + must point to the same agent as ``parent``. + + This corresponds to the ``entity_type_names`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, entity_type_names]) + if request is 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 = entity_type.BatchDeleteEntityTypesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entity_type_names: + request.entity_type_names.extend(entity_type_names) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_delete_entity_types, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def batch_create_entities(self, + request: Union[entity_type.BatchCreateEntitiesRequest, dict] = None, + *, + parent: str = None, + entities: Sequence[entity_type.EntityType.Entity] = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates multiple new entities in the specified entity type. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.BatchCreateEntitiesRequest, dict]): + The request object. The request message for + [EntityTypes.BatchCreateEntities][google.cloud.dialogflow.v2beta1.EntityTypes.BatchCreateEntities]. + parent (:class:`str`): + Required. The name of the entity type to create entities + in. Supported formats: + + - ``projects//agent/entityTypes/`` + - ``projects//locations//agent/entityTypes/`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entities (:class:`Sequence[google.cloud.dialogflow_v2beta1.types.EntityType.Entity]`): + Required. The entities to create. + This corresponds to the ``entities`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (:class:`str`): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, entities, language_code]) + if request is 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 = entity_type.BatchCreateEntitiesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if language_code is not None: + request.language_code = language_code + if entities: + request.entities.extend(entities) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_create_entities, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def batch_update_entities(self, + request: Union[entity_type.BatchUpdateEntitiesRequest, dict] = None, + *, + parent: str = None, + entities: Sequence[entity_type.EntityType.Entity] = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates or creates multiple entities in the specified entity + type. This method does not affect entities in the entity type + that aren't explicitly specified in the request. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.BatchUpdateEntitiesRequest, dict]): + The request object. The request message for + [EntityTypes.BatchUpdateEntities][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntities]. + parent (:class:`str`): + Required. The name of the entity type to update or + create entities in. Supported formats: + + - ``projects//agent/entityTypes/`` + - ``projects//locations//agent/entityTypes/`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entities (:class:`Sequence[google.cloud.dialogflow_v2beta1.types.EntityType.Entity]`): + Required. The entities to update or + create. + + This corresponds to the ``entities`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (:class:`str`): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, entities, language_code]) + if request is 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 = entity_type.BatchUpdateEntitiesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if language_code is not None: + request.language_code = language_code + if entities: + request.entities.extend(entities) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_update_entities, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def batch_delete_entities(self, + request: Union[entity_type.BatchDeleteEntitiesRequest, dict] = None, + *, + parent: str = None, + entity_values: Sequence[str] = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes entities in the specified entity type. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.BatchDeleteEntitiesRequest, dict]): + The request object. The request message for + [EntityTypes.BatchDeleteEntities][google.cloud.dialogflow.v2beta1.EntityTypes.BatchDeleteEntities]. + parent (:class:`str`): + Required. The name of the entity type to delete entries + for. Supported formats: + + - ``projects//agent/entityTypes/`` + - ``projects//locations//agent/entityTypes/`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entity_values (:class:`Sequence[str]`): + Required. The reference ``values`` of the entities to + delete. Note that these are not fully-qualified names, + i.e. they don't start with ``projects/``. + + This corresponds to the ``entity_values`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (:class:`str`): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, entity_values, language_code]) + if request is 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 = entity_type.BatchDeleteEntitiesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if language_code is not None: + request.language_code = language_code + if entity_values: + request.entity_values.extend(entity_values) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_delete_entities, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "EntityTypesAsyncClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/client.py new file mode 100644 index 000000000..e0a5c821c --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/client.py @@ -0,0 +1,1500 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.dialogflow_v2beta1.services.entity_types import pagers +from google.cloud.dialogflow_v2beta1.types import entity_type +from google.cloud.dialogflow_v2beta1.types import entity_type as gcd_entity_type +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import EntityTypesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import EntityTypesGrpcTransport +from .transports.grpc_asyncio import EntityTypesGrpcAsyncIOTransport + + +class EntityTypesClientMeta(type): + """Metaclass for the EntityTypes 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[EntityTypesTransport]] + _transport_registry["grpc"] = EntityTypesGrpcTransport + _transport_registry["grpc_asyncio"] = EntityTypesGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[EntityTypesTransport]: + """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 EntityTypesClient(metaclass=EntityTypesClientMeta): + """Service for managing + [EntityTypes][google.cloud.dialogflow.v2beta1.EntityType]. + """ + + @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 = "dialogflow.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: + EntityTypesClient: 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: + EntityTypesClient: 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) -> EntityTypesTransport: + """Returns the transport used by the client instance. + + Returns: + EntityTypesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def entity_type_path(project: str,entity_type: str,) -> str: + """Returns a fully-qualified entity_type string.""" + return "projects/{project}/agent/entityTypes/{entity_type}".format(project=project, entity_type=entity_type, ) + + @staticmethod + def parse_entity_type_path(path: str) -> Dict[str,str]: + """Parses a entity_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/entityTypes/(?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, EntityTypesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the entity types 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, EntityTypesTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, EntityTypesTransport): + # transport is a EntityTypesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_entity_types(self, + request: Union[entity_type.ListEntityTypesRequest, dict] = None, + *, + parent: str = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEntityTypesPager: + r"""Returns the list of all entity types in the specified + agent. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListEntityTypesRequest, dict]): + The request object. The request message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.ListEntityTypes]. + parent (str): + Required. The agent to list all entity types from. + Supported formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.services.entity_types.pagers.ListEntityTypesPager: + The response message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.ListEntityTypes]. + + 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, language_code]) + if request is 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 entity_type.ListEntityTypesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, entity_type.ListEntityTypesRequest): + request = entity_type.ListEntityTypesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if language_code is not None: + request.language_code = language_code + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_entity_types] + + # Certain 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.ListEntityTypesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_entity_type(self, + request: Union[entity_type.GetEntityTypeRequest, dict] = None, + *, + name: str = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> entity_type.EntityType: + r"""Retrieves the specified entity type. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetEntityTypeRequest, dict]): + The request object. The request message for + [EntityTypes.GetEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.GetEntityType]. + name (str): + Required. The name of the entity type. Supported + formats: + + - ``projects//agent/entityTypes/`` + - ``projects//locations//agent/entityTypes/`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.EntityType: + Each intent parameter has a type, called the entity type, which dictates + exactly how data from an end-user expression is + extracted. + + Dialogflow provides predefined system entities that + can match many common types of data. For example, + there are system entities for matching dates, times, + colors, email addresses, and so on. You can also + create your own custom entities for matching custom + data. For example, you could define a vegetable + entity that can match the types of vegetables + available for purchase with a grocery store agent. + + For more information, see the [Entity + guide](\ https://cloud.google.com/dialogflow/docs/entities-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, language_code]) + if request is 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 entity_type.GetEntityTypeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, entity_type.GetEntityTypeRequest): + request = entity_type.GetEntityTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if language_code is not None: + request.language_code = language_code + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_entity_type] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_entity_type(self, + request: Union[gcd_entity_type.CreateEntityTypeRequest, dict] = None, + *, + parent: str = None, + entity_type: gcd_entity_type.EntityType = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_entity_type.EntityType: + r"""Creates an entity type in the specified agent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.CreateEntityTypeRequest, dict]): + The request object. The request message for + [EntityTypes.CreateEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.CreateEntityType]. + parent (str): + Required. The agent to create a entity type for. + Supported formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entity_type (google.cloud.dialogflow_v2beta1.types.EntityType): + Required. The entity type to create. + This corresponds to the ``entity_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.EntityType: + Each intent parameter has a type, called the entity type, which dictates + exactly how data from an end-user expression is + extracted. + + Dialogflow provides predefined system entities that + can match many common types of data. For example, + there are system entities for matching dates, times, + colors, email addresses, and so on. You can also + create your own custom entities for matching custom + data. For example, you could define a vegetable + entity that can match the types of vegetables + available for purchase with a grocery store agent. + + For more information, see the [Entity + guide](\ https://cloud.google.com/dialogflow/docs/entities-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, entity_type, language_code]) + if request is 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 gcd_entity_type.CreateEntityTypeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_entity_type.CreateEntityTypeRequest): + request = gcd_entity_type.CreateEntityTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entity_type is not None: + request.entity_type = entity_type + if language_code is not None: + request.language_code = language_code + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_entity_type] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_entity_type(self, + request: Union[gcd_entity_type.UpdateEntityTypeRequest, dict] = None, + *, + entity_type: gcd_entity_type.EntityType = None, + language_code: str = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_entity_type.EntityType: + r"""Updates the specified entity type. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.UpdateEntityTypeRequest, dict]): + The request object. The request message for + [EntityTypes.UpdateEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.UpdateEntityType]. + entity_type (google.cloud.dialogflow_v2beta1.types.EntityType): + Required. The entity type to update. + This corresponds to the ``entity_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.EntityType: + Each intent parameter has a type, called the entity type, which dictates + exactly how data from an end-user expression is + extracted. + + Dialogflow provides predefined system entities that + can match many common types of data. For example, + there are system entities for matching dates, times, + colors, email addresses, and so on. You can also + create your own custom entities for matching custom + data. For example, you could define a vegetable + entity that can match the types of vegetables + available for purchase with a grocery store agent. + + For more information, see the [Entity + guide](\ https://cloud.google.com/dialogflow/docs/entities-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([entity_type, language_code, 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 gcd_entity_type.UpdateEntityTypeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_entity_type.UpdateEntityTypeRequest): + request = gcd_entity_type.UpdateEntityTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if entity_type is not None: + request.entity_type = entity_type + if language_code is not None: + request.language_code = language_code + 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_entity_type] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("entity_type.name", request.entity_type.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_entity_type(self, + request: Union[entity_type.DeleteEntityTypeRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified entity type. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.DeleteEntityTypeRequest, dict]): + The request object. The request message for + [EntityTypes.DeleteEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.DeleteEntityType]. + name (str): + Required. The name of the entity type to delete. + Supported formats: + + - ``projects//agent/entityTypes/`` + - ``projects//locations//agent/entityTypes/`` + + 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 entity_type.DeleteEntityTypeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, entity_type.DeleteEntityTypeRequest): + request = entity_type.DeleteEntityTypeRequest(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_entity_type] + + # Certain 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 batch_update_entity_types(self, + request: Union[entity_type.BatchUpdateEntityTypesRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates/Creates multiple entity types in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [BatchUpdateEntityTypesResponse][google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse] + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.BatchUpdateEntityTypesRequest, dict]): + The request object. The request message for + [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.dialogflow_v2beta1.types.BatchUpdateEntityTypesResponse` + The response message for + [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a entity_type.BatchUpdateEntityTypesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, entity_type.BatchUpdateEntityTypesRequest): + request = entity_type.BatchUpdateEntityTypesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_update_entity_types] + + # Certain 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, + entity_type.BatchUpdateEntityTypesResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def batch_delete_entity_types(self, + request: Union[entity_type.BatchDeleteEntityTypesRequest, dict] = None, + *, + parent: str = None, + entity_type_names: Sequence[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes entity types in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.BatchDeleteEntityTypesRequest, dict]): + The request object. The request message for + [EntityTypes.BatchDeleteEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchDeleteEntityTypes]. + parent (str): + Required. The name of the agent to delete all entities + types for. Supported formats: + + - ``projects//agent``, + - ``projects//locations//agent``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entity_type_names (Sequence[str]): + Required. The names entity types to delete. All names + must point to the same agent as ``parent``. + + This corresponds to the ``entity_type_names`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, entity_type_names]) + if request is 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 entity_type.BatchDeleteEntityTypesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, entity_type.BatchDeleteEntityTypesRequest): + request = entity_type.BatchDeleteEntityTypesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entity_type_names is not None: + request.entity_type_names = entity_type_names + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_delete_entity_types] + + # Certain 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, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def batch_create_entities(self, + request: Union[entity_type.BatchCreateEntitiesRequest, dict] = None, + *, + parent: str = None, + entities: Sequence[entity_type.EntityType.Entity] = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates multiple new entities in the specified entity type. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.BatchCreateEntitiesRequest, dict]): + The request object. The request message for + [EntityTypes.BatchCreateEntities][google.cloud.dialogflow.v2beta1.EntityTypes.BatchCreateEntities]. + parent (str): + Required. The name of the entity type to create entities + in. Supported formats: + + - ``projects//agent/entityTypes/`` + - ``projects//locations//agent/entityTypes/`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entities (Sequence[google.cloud.dialogflow_v2beta1.types.EntityType.Entity]): + Required. The entities to create. + This corresponds to the ``entities`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, entities, language_code]) + if request is 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 entity_type.BatchCreateEntitiesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, entity_type.BatchCreateEntitiesRequest): + request = entity_type.BatchCreateEntitiesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entities is not None: + request.entities = entities + if language_code is not None: + request.language_code = language_code + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_create_entities] + + # Certain 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, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def batch_update_entities(self, + request: Union[entity_type.BatchUpdateEntitiesRequest, dict] = None, + *, + parent: str = None, + entities: Sequence[entity_type.EntityType.Entity] = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates or creates multiple entities in the specified entity + type. This method does not affect entities in the entity type + that aren't explicitly specified in the request. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.BatchUpdateEntitiesRequest, dict]): + The request object. The request message for + [EntityTypes.BatchUpdateEntities][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntities]. + parent (str): + Required. The name of the entity type to update or + create entities in. Supported formats: + + - ``projects//agent/entityTypes/`` + - ``projects//locations//agent/entityTypes/`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entities (Sequence[google.cloud.dialogflow_v2beta1.types.EntityType.Entity]): + Required. The entities to update or + create. + + This corresponds to the ``entities`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, entities, language_code]) + if request is 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 entity_type.BatchUpdateEntitiesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, entity_type.BatchUpdateEntitiesRequest): + request = entity_type.BatchUpdateEntitiesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entities is not None: + request.entities = entities + if language_code is not None: + request.language_code = language_code + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_update_entities] + + # Certain 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, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def batch_delete_entities(self, + request: Union[entity_type.BatchDeleteEntitiesRequest, dict] = None, + *, + parent: str = None, + entity_values: Sequence[str] = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes entities in the specified entity type. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.BatchDeleteEntitiesRequest, dict]): + The request object. The request message for + [EntityTypes.BatchDeleteEntities][google.cloud.dialogflow.v2beta1.EntityTypes.BatchDeleteEntities]. + parent (str): + Required. The name of the entity type to delete entries + for. Supported formats: + + - ``projects//agent/entityTypes/`` + - ``projects//locations//agent/entityTypes/`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entity_values (Sequence[str]): + Required. The reference ``values`` of the entities to + delete. Note that these are not fully-qualified names, + i.e. they don't start with ``projects/``. + + This corresponds to the ``entity_values`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, entity_values, language_code]) + if request is 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 entity_type.BatchDeleteEntitiesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, entity_type.BatchDeleteEntitiesRequest): + request = entity_type.BatchDeleteEntitiesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entity_values is not None: + request.entity_values = entity_values + if language_code is not None: + request.language_code = language_code + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_delete_entities] + + # Certain 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, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "EntityTypesClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/pagers.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/pagers.py new file mode 100644 index 000000000..0a59c502a --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflow_v2beta1.types import entity_type + + +class ListEntityTypesPager: + """A pager for iterating through ``list_entity_types`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListEntityTypesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``entity_types`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEntityTypes`` requests and continue to iterate + through the ``entity_types`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListEntityTypesResponse` + 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[..., entity_type.ListEntityTypesResponse], + request: entity_type.ListEntityTypesRequest, + response: entity_type.ListEntityTypesResponse, + *, + 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.dialogflow_v2beta1.types.ListEntityTypesRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListEntityTypesResponse): + 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 = entity_type.ListEntityTypesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[entity_type.ListEntityTypesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[entity_type.EntityType]: + for page in self.pages: + yield from page.entity_types + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEntityTypesAsyncPager: + """A pager for iterating through ``list_entity_types`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListEntityTypesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``entity_types`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEntityTypes`` requests and continue to iterate + through the ``entity_types`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListEntityTypesResponse` + 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[entity_type.ListEntityTypesResponse]], + request: entity_type.ListEntityTypesRequest, + response: entity_type.ListEntityTypesResponse, + *, + 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.dialogflow_v2beta1.types.ListEntityTypesRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListEntityTypesResponse): + 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 = entity_type.ListEntityTypesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[entity_type.ListEntityTypesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[entity_type.EntityType]: + async def async_generator(): + async for page in self.pages: + for response in page.entity_types: + 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/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/__init__.py new file mode 100644 index 000000000..1a2aa82dc --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/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 EntityTypesTransport +from .grpc import EntityTypesGrpcTransport +from .grpc_asyncio import EntityTypesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[EntityTypesTransport]] +_transport_registry['grpc'] = EntityTypesGrpcTransport +_transport_registry['grpc_asyncio'] = EntityTypesGrpcAsyncIOTransport + +__all__ = ( + 'EntityTypesTransport', + 'EntityTypesGrpcTransport', + 'EntityTypesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/base.py new file mode 100644 index 000000000..eda3c7267 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/base.py @@ -0,0 +1,282 @@ +# -*- 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.types import entity_type +from google.cloud.dialogflow_v2beta1.types import entity_type as gcd_entity_type +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-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class EntityTypesTransport(abc.ABC): + """Abstract transport class for EntityTypes.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_entity_types: gapic_v1.method.wrap_method( + self.list_entity_types, + default_timeout=None, + client_info=client_info, + ), + self.get_entity_type: gapic_v1.method.wrap_method( + self.get_entity_type, + default_timeout=None, + client_info=client_info, + ), + self.create_entity_type: gapic_v1.method.wrap_method( + self.create_entity_type, + default_timeout=None, + client_info=client_info, + ), + self.update_entity_type: gapic_v1.method.wrap_method( + self.update_entity_type, + default_timeout=None, + client_info=client_info, + ), + self.delete_entity_type: gapic_v1.method.wrap_method( + self.delete_entity_type, + default_timeout=None, + client_info=client_info, + ), + self.batch_update_entity_types: gapic_v1.method.wrap_method( + self.batch_update_entity_types, + default_timeout=None, + client_info=client_info, + ), + self.batch_delete_entity_types: gapic_v1.method.wrap_method( + self.batch_delete_entity_types, + default_timeout=None, + client_info=client_info, + ), + self.batch_create_entities: gapic_v1.method.wrap_method( + self.batch_create_entities, + default_timeout=None, + client_info=client_info, + ), + self.batch_update_entities: gapic_v1.method.wrap_method( + self.batch_update_entities, + default_timeout=None, + client_info=client_info, + ), + self.batch_delete_entities: gapic_v1.method.wrap_method( + self.batch_delete_entities, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_entity_types(self) -> Callable[ + [entity_type.ListEntityTypesRequest], + Union[ + entity_type.ListEntityTypesResponse, + Awaitable[entity_type.ListEntityTypesResponse] + ]]: + raise NotImplementedError() + + @property + def get_entity_type(self) -> Callable[ + [entity_type.GetEntityTypeRequest], + Union[ + entity_type.EntityType, + Awaitable[entity_type.EntityType] + ]]: + raise NotImplementedError() + + @property + def create_entity_type(self) -> Callable[ + [gcd_entity_type.CreateEntityTypeRequest], + Union[ + gcd_entity_type.EntityType, + Awaitable[gcd_entity_type.EntityType] + ]]: + raise NotImplementedError() + + @property + def update_entity_type(self) -> Callable[ + [gcd_entity_type.UpdateEntityTypeRequest], + Union[ + gcd_entity_type.EntityType, + Awaitable[gcd_entity_type.EntityType] + ]]: + raise NotImplementedError() + + @property + def delete_entity_type(self) -> Callable[ + [entity_type.DeleteEntityTypeRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def batch_update_entity_types(self) -> Callable[ + [entity_type.BatchUpdateEntityTypesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def batch_delete_entity_types(self) -> Callable[ + [entity_type.BatchDeleteEntityTypesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def batch_create_entities(self) -> Callable[ + [entity_type.BatchCreateEntitiesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def batch_update_entities(self) -> Callable[ + [entity_type.BatchUpdateEntitiesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def batch_delete_entities(self) -> Callable[ + [entity_type.BatchDeleteEntitiesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'EntityTypesTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc.py new file mode 100644 index 000000000..df100187f --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc.py @@ -0,0 +1,595 @@ +# -*- 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 +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import entity_type +from google.cloud.dialogflow_v2beta1.types import entity_type as gcd_entity_type +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import EntityTypesTransport, DEFAULT_CLIENT_INFO + + +class EntityTypesGrpcTransport(EntityTypesTransport): + """gRPC backend transport for EntityTypes. + + Service for managing + [EntityTypes][google.cloud.dialogflow.v2beta1.EntityType]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 = 'dialogflow.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 list_entity_types(self) -> Callable[ + [entity_type.ListEntityTypesRequest], + entity_type.ListEntityTypesResponse]: + r"""Return a callable for the list entity types method over gRPC. + + Returns the list of all entity types in the specified + agent. + + Returns: + Callable[[~.ListEntityTypesRequest], + ~.ListEntityTypesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entity_types' not in self._stubs: + self._stubs['list_entity_types'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.EntityTypes/ListEntityTypes', + request_serializer=entity_type.ListEntityTypesRequest.serialize, + response_deserializer=entity_type.ListEntityTypesResponse.deserialize, + ) + return self._stubs['list_entity_types'] + + @property + def get_entity_type(self) -> Callable[ + [entity_type.GetEntityTypeRequest], + entity_type.EntityType]: + r"""Return a callable for the get entity type method over gRPC. + + Retrieves the specified entity type. + + Returns: + Callable[[~.GetEntityTypeRequest], + ~.EntityType]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entity_type' not in self._stubs: + self._stubs['get_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.EntityTypes/GetEntityType', + request_serializer=entity_type.GetEntityTypeRequest.serialize, + response_deserializer=entity_type.EntityType.deserialize, + ) + return self._stubs['get_entity_type'] + + @property + def create_entity_type(self) -> Callable[ + [gcd_entity_type.CreateEntityTypeRequest], + gcd_entity_type.EntityType]: + r"""Return a callable for the create entity type method over gRPC. + + Creates an entity type in the specified agent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.CreateEntityTypeRequest], + ~.EntityType]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entity_type' not in self._stubs: + self._stubs['create_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.EntityTypes/CreateEntityType', + request_serializer=gcd_entity_type.CreateEntityTypeRequest.serialize, + response_deserializer=gcd_entity_type.EntityType.deserialize, + ) + return self._stubs['create_entity_type'] + + @property + def update_entity_type(self) -> Callable[ + [gcd_entity_type.UpdateEntityTypeRequest], + gcd_entity_type.EntityType]: + r"""Return a callable for the update entity type method over gRPC. + + Updates the specified entity type. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.UpdateEntityTypeRequest], + ~.EntityType]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entity_type' not in self._stubs: + self._stubs['update_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.EntityTypes/UpdateEntityType', + request_serializer=gcd_entity_type.UpdateEntityTypeRequest.serialize, + response_deserializer=gcd_entity_type.EntityType.deserialize, + ) + return self._stubs['update_entity_type'] + + @property + def delete_entity_type(self) -> Callable[ + [entity_type.DeleteEntityTypeRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete entity type method over gRPC. + + Deletes the specified entity type. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.DeleteEntityTypeRequest], + ~.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_entity_type' not in self._stubs: + self._stubs['delete_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.EntityTypes/DeleteEntityType', + request_serializer=entity_type.DeleteEntityTypeRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_entity_type'] + + @property + def batch_update_entity_types(self) -> Callable[ + [entity_type.BatchUpdateEntityTypesRequest], + operations_pb2.Operation]: + r"""Return a callable for the batch update entity types method over gRPC. + + Updates/Creates multiple entity types in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [BatchUpdateEntityTypesResponse][google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse] + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.BatchUpdateEntityTypesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_update_entity_types' not in self._stubs: + self._stubs['batch_update_entity_types'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.EntityTypes/BatchUpdateEntityTypes', + request_serializer=entity_type.BatchUpdateEntityTypesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_update_entity_types'] + + @property + def batch_delete_entity_types(self) -> Callable[ + [entity_type.BatchDeleteEntityTypesRequest], + operations_pb2.Operation]: + r"""Return a callable for the batch delete entity types method over gRPC. + + Deletes entity types in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.BatchDeleteEntityTypesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_delete_entity_types' not in self._stubs: + self._stubs['batch_delete_entity_types'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.EntityTypes/BatchDeleteEntityTypes', + request_serializer=entity_type.BatchDeleteEntityTypesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_delete_entity_types'] + + @property + def batch_create_entities(self) -> Callable[ + [entity_type.BatchCreateEntitiesRequest], + operations_pb2.Operation]: + r"""Return a callable for the batch create entities method over gRPC. + + Creates multiple new entities in the specified entity type. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.BatchCreateEntitiesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_create_entities' not in self._stubs: + self._stubs['batch_create_entities'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.EntityTypes/BatchCreateEntities', + request_serializer=entity_type.BatchCreateEntitiesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_create_entities'] + + @property + def batch_update_entities(self) -> Callable[ + [entity_type.BatchUpdateEntitiesRequest], + operations_pb2.Operation]: + r"""Return a callable for the batch update entities method over gRPC. + + Updates or creates multiple entities in the specified entity + type. This method does not affect entities in the entity type + that aren't explicitly specified in the request. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Returns: + Callable[[~.BatchUpdateEntitiesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_update_entities' not in self._stubs: + self._stubs['batch_update_entities'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.EntityTypes/BatchUpdateEntities', + request_serializer=entity_type.BatchUpdateEntitiesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_update_entities'] + + @property + def batch_delete_entities(self) -> Callable[ + [entity_type.BatchDeleteEntitiesRequest], + operations_pb2.Operation]: + r"""Return a callable for the batch delete entities method over gRPC. + + Deletes entities in the specified entity type. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.BatchDeleteEntitiesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_delete_entities' not in self._stubs: + self._stubs['batch_delete_entities'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.EntityTypes/BatchDeleteEntities', + request_serializer=entity_type.BatchDeleteEntitiesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_delete_entities'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'EntityTypesGrpcTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc_asyncio.py new file mode 100644 index 000000000..d4d37af1c --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc_asyncio.py @@ -0,0 +1,599 @@ +# -*- 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 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import entity_type +from google.cloud.dialogflow_v2beta1.types import entity_type as gcd_entity_type +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import EntityTypesTransport, DEFAULT_CLIENT_INFO +from .grpc import EntityTypesGrpcTransport + + +class EntityTypesGrpcAsyncIOTransport(EntityTypesTransport): + """gRPC AsyncIO backend transport for EntityTypes. + + Service for managing + [EntityTypes][google.cloud.dialogflow.v2beta1.EntityType]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 list_entity_types(self) -> Callable[ + [entity_type.ListEntityTypesRequest], + Awaitable[entity_type.ListEntityTypesResponse]]: + r"""Return a callable for the list entity types method over gRPC. + + Returns the list of all entity types in the specified + agent. + + Returns: + Callable[[~.ListEntityTypesRequest], + Awaitable[~.ListEntityTypesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entity_types' not in self._stubs: + self._stubs['list_entity_types'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.EntityTypes/ListEntityTypes', + request_serializer=entity_type.ListEntityTypesRequest.serialize, + response_deserializer=entity_type.ListEntityTypesResponse.deserialize, + ) + return self._stubs['list_entity_types'] + + @property + def get_entity_type(self) -> Callable[ + [entity_type.GetEntityTypeRequest], + Awaitable[entity_type.EntityType]]: + r"""Return a callable for the get entity type method over gRPC. + + Retrieves the specified entity type. + + Returns: + Callable[[~.GetEntityTypeRequest], + Awaitable[~.EntityType]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entity_type' not in self._stubs: + self._stubs['get_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.EntityTypes/GetEntityType', + request_serializer=entity_type.GetEntityTypeRequest.serialize, + response_deserializer=entity_type.EntityType.deserialize, + ) + return self._stubs['get_entity_type'] + + @property + def create_entity_type(self) -> Callable[ + [gcd_entity_type.CreateEntityTypeRequest], + Awaitable[gcd_entity_type.EntityType]]: + r"""Return a callable for the create entity type method over gRPC. + + Creates an entity type in the specified agent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.CreateEntityTypeRequest], + Awaitable[~.EntityType]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entity_type' not in self._stubs: + self._stubs['create_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.EntityTypes/CreateEntityType', + request_serializer=gcd_entity_type.CreateEntityTypeRequest.serialize, + response_deserializer=gcd_entity_type.EntityType.deserialize, + ) + return self._stubs['create_entity_type'] + + @property + def update_entity_type(self) -> Callable[ + [gcd_entity_type.UpdateEntityTypeRequest], + Awaitable[gcd_entity_type.EntityType]]: + r"""Return a callable for the update entity type method over gRPC. + + Updates the specified entity type. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.UpdateEntityTypeRequest], + Awaitable[~.EntityType]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_entity_type' not in self._stubs: + self._stubs['update_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.EntityTypes/UpdateEntityType', + request_serializer=gcd_entity_type.UpdateEntityTypeRequest.serialize, + response_deserializer=gcd_entity_type.EntityType.deserialize, + ) + return self._stubs['update_entity_type'] + + @property + def delete_entity_type(self) -> Callable[ + [entity_type.DeleteEntityTypeRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete entity type method over gRPC. + + Deletes the specified entity type. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.DeleteEntityTypeRequest], + 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_entity_type' not in self._stubs: + self._stubs['delete_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.EntityTypes/DeleteEntityType', + request_serializer=entity_type.DeleteEntityTypeRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_entity_type'] + + @property + def batch_update_entity_types(self) -> Callable[ + [entity_type.BatchUpdateEntityTypesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the batch update entity types method over gRPC. + + Updates/Creates multiple entity types in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [BatchUpdateEntityTypesResponse][google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse] + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.BatchUpdateEntityTypesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_update_entity_types' not in self._stubs: + self._stubs['batch_update_entity_types'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.EntityTypes/BatchUpdateEntityTypes', + request_serializer=entity_type.BatchUpdateEntityTypesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_update_entity_types'] + + @property + def batch_delete_entity_types(self) -> Callable[ + [entity_type.BatchDeleteEntityTypesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the batch delete entity types method over gRPC. + + Deletes entity types in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.BatchDeleteEntityTypesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_delete_entity_types' not in self._stubs: + self._stubs['batch_delete_entity_types'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.EntityTypes/BatchDeleteEntityTypes', + request_serializer=entity_type.BatchDeleteEntityTypesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_delete_entity_types'] + + @property + def batch_create_entities(self) -> Callable[ + [entity_type.BatchCreateEntitiesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the batch create entities method over gRPC. + + Creates multiple new entities in the specified entity type. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.BatchCreateEntitiesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_create_entities' not in self._stubs: + self._stubs['batch_create_entities'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.EntityTypes/BatchCreateEntities', + request_serializer=entity_type.BatchCreateEntitiesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_create_entities'] + + @property + def batch_update_entities(self) -> Callable[ + [entity_type.BatchUpdateEntitiesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the batch update entities method over gRPC. + + Updates or creates multiple entities in the specified entity + type. This method does not affect entities in the entity type + that aren't explicitly specified in the request. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Returns: + Callable[[~.BatchUpdateEntitiesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_update_entities' not in self._stubs: + self._stubs['batch_update_entities'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.EntityTypes/BatchUpdateEntities', + request_serializer=entity_type.BatchUpdateEntitiesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_update_entities'] + + @property + def batch_delete_entities(self) -> Callable[ + [entity_type.BatchDeleteEntitiesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the batch delete entities method over gRPC. + + Deletes entities in the specified entity type. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.BatchDeleteEntitiesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_delete_entities' not in self._stubs: + self._stubs['batch_delete_entities'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.EntityTypes/BatchDeleteEntities', + request_serializer=entity_type.BatchDeleteEntitiesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_delete_entities'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'EntityTypesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/__init__.py new file mode 100644 index 000000000..a3ad29ecd --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/__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 EnvironmentsClient +from .async_client import EnvironmentsAsyncClient + +__all__ = ( + 'EnvironmentsClient', + 'EnvironmentsAsyncClient', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/async_client.py new file mode 100644 index 000000000..5c439a313 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/async_client.py @@ -0,0 +1,616 @@ +# -*- 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 + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2beta1.services.environments import pagers +from google.cloud.dialogflow_v2beta1.types import environment +from google.cloud.dialogflow_v2beta1.types import fulfillment +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport +from .client import EnvironmentsClient + + +class EnvironmentsAsyncClient: + """Service for managing + [Environments][google.cloud.dialogflow.v2beta1.Environment]. + """ + + _client: EnvironmentsClient + + DEFAULT_ENDPOINT = EnvironmentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = EnvironmentsClient.DEFAULT_MTLS_ENDPOINT + + environment_path = staticmethod(EnvironmentsClient.environment_path) + parse_environment_path = staticmethod(EnvironmentsClient.parse_environment_path) + fulfillment_path = staticmethod(EnvironmentsClient.fulfillment_path) + parse_fulfillment_path = staticmethod(EnvironmentsClient.parse_fulfillment_path) + version_path = staticmethod(EnvironmentsClient.version_path) + parse_version_path = staticmethod(EnvironmentsClient.parse_version_path) + common_billing_account_path = staticmethod(EnvironmentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(EnvironmentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(EnvironmentsClient.common_folder_path) + parse_common_folder_path = staticmethod(EnvironmentsClient.parse_common_folder_path) + common_organization_path = staticmethod(EnvironmentsClient.common_organization_path) + parse_common_organization_path = staticmethod(EnvironmentsClient.parse_common_organization_path) + common_project_path = staticmethod(EnvironmentsClient.common_project_path) + parse_common_project_path = staticmethod(EnvironmentsClient.parse_common_project_path) + common_location_path = staticmethod(EnvironmentsClient.common_location_path) + parse_common_location_path = staticmethod(EnvironmentsClient.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: + EnvironmentsAsyncClient: The constructed client. + """ + return EnvironmentsClient.from_service_account_info.__func__(EnvironmentsAsyncClient, 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: + EnvironmentsAsyncClient: The constructed client. + """ + return EnvironmentsClient.from_service_account_file.__func__(EnvironmentsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> EnvironmentsTransport: + """Returns the transport used by the client instance. + + Returns: + EnvironmentsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(EnvironmentsClient).get_transport_class, type(EnvironmentsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, EnvironmentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the environments 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, ~.EnvironmentsTransport]): 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 = EnvironmentsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_environments(self, + request: Union[environment.ListEnvironmentsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEnvironmentsAsyncPager: + r"""Returns the list of all non-draft environments of the + specified agent. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListEnvironmentsRequest, dict]): + The request object. The request message for + [Environments.ListEnvironments][google.cloud.dialogflow.v2beta1.Environments.ListEnvironments]. + parent (:class:`str`): + Required. The agent to list all environments from. + Format: + + - ``projects//agent`` + - ``projects//locations//agent`` + + 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.dialogflow_v2beta1.services.environments.pagers.ListEnvironmentsAsyncPager: + The response message for + [Environments.ListEnvironments][google.cloud.dialogflow.v2beta1.Environments.ListEnvironments]. + + 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 = environment.ListEnvironmentsRequest(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_environments, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEnvironmentsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_environment(self, + request: Union[environment.GetEnvironmentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Retrieves the specified agent environment. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetEnvironmentRequest, dict]): + The request object. The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.v2beta1.Environments.GetEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + request = environment.GetEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_environment(self, + request: Union[environment.CreateEnvironmentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Creates an agent environment. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.CreateEnvironmentRequest, dict]): + The request object. The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.v2beta1.Environments.CreateEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + request = environment.CreateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_environment(self, + request: Union[environment.UpdateEnvironmentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment keeps on serving the previous version + of the agent. After the new agent version is done loading, the + environment is set back to the ``RUNNING`` state. You can use + "-" as Environment ID in environment name to update version in + "draft" environment. WARNING: this will negate all recent + changes to draft and can't be undone. You may want to save the + draft to a version before calling this function. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.UpdateEnvironmentRequest, dict]): + The request object. The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.v2beta1.Environments.UpdateEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + request = environment.UpdateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment.name", request.environment.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_environment(self, + request: Union[environment.DeleteEnvironmentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified agent environment. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.DeleteEnvironmentRequest, dict]): + The request object. The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.v2beta1.Environments.DeleteEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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. + request = environment.DeleteEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_environment_history(self, + request: Union[environment.GetEnvironmentHistoryRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GetEnvironmentHistoryAsyncPager: + r"""Gets the history of the specified environment. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetEnvironmentHistoryRequest, dict]): + The request object. The request message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.services.environments.pagers.GetEnvironmentHistoryAsyncPager: + The response message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = environment.GetEnvironmentHistoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_environment_history, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.GetEnvironmentHistoryAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "EnvironmentsAsyncClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/client.py new file mode 100644 index 000000000..77ff5d2ac --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/client.py @@ -0,0 +1,837 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2beta1.services.environments import pagers +from google.cloud.dialogflow_v2beta1.types import environment +from google.cloud.dialogflow_v2beta1.types import fulfillment +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import EnvironmentsGrpcTransport +from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport + + +class EnvironmentsClientMeta(type): + """Metaclass for the Environments 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[EnvironmentsTransport]] + _transport_registry["grpc"] = EnvironmentsGrpcTransport + _transport_registry["grpc_asyncio"] = EnvironmentsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[EnvironmentsTransport]: + """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 EnvironmentsClient(metaclass=EnvironmentsClientMeta): + """Service for managing + [Environments][google.cloud.dialogflow.v2beta1.Environment]. + """ + + @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 = "dialogflow.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: + EnvironmentsClient: 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: + EnvironmentsClient: 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) -> EnvironmentsTransport: + """Returns the transport used by the client instance. + + Returns: + EnvironmentsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def environment_path(project: str,environment: str,) -> str: + """Returns a fully-qualified environment string.""" + return "projects/{project}/agent/environments/{environment}".format(project=project, environment=environment, ) + + @staticmethod + def parse_environment_path(path: str) -> Dict[str,str]: + """Parses a environment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/environments/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def fulfillment_path(project: str,) -> str: + """Returns a fully-qualified fulfillment string.""" + return "projects/{project}/agent/fulfillment".format(project=project, ) + + @staticmethod + def parse_fulfillment_path(path: str) -> Dict[str,str]: + """Parses a fulfillment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/fulfillment$", path) + return m.groupdict() if m else {} + + @staticmethod + def version_path(project: str,version: str,) -> str: + """Returns a fully-qualified version string.""" + return "projects/{project}/agent/versions/{version}".format(project=project, version=version, ) + + @staticmethod + def parse_version_path(path: str) -> Dict[str,str]: + """Parses a version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/versions/(?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, EnvironmentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the environments 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, EnvironmentsTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, EnvironmentsTransport): + # transport is a EnvironmentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_environments(self, + request: Union[environment.ListEnvironmentsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEnvironmentsPager: + r"""Returns the list of all non-draft environments of the + specified agent. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListEnvironmentsRequest, dict]): + The request object. The request message for + [Environments.ListEnvironments][google.cloud.dialogflow.v2beta1.Environments.ListEnvironments]. + parent (str): + Required. The agent to list all environments from. + Format: + + - ``projects//agent`` + - ``projects//locations//agent`` + + 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.dialogflow_v2beta1.services.environments.pagers.ListEnvironmentsPager: + The response message for + [Environments.ListEnvironments][google.cloud.dialogflow.v2beta1.Environments.ListEnvironments]. + + 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 environment.ListEnvironmentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.ListEnvironmentsRequest): + request = environment.ListEnvironmentsRequest(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_environments] + + # Certain 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.ListEnvironmentsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_environment(self, + request: Union[environment.GetEnvironmentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Retrieves the specified agent environment. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetEnvironmentRequest, dict]): + The request object. The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.v2beta1.Environments.GetEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.GetEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.GetEnvironmentRequest): + request = environment.GetEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_environment(self, + request: Union[environment.CreateEnvironmentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Creates an agent environment. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.CreateEnvironmentRequest, dict]): + The request object. The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.v2beta1.Environments.CreateEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.CreateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.CreateEnvironmentRequest): + request = environment.CreateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_environment(self, + request: Union[environment.UpdateEnvironmentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment keeps on serving the previous version + of the agent. After the new agent version is done loading, the + environment is set back to the ``RUNNING`` state. You can use + "-" as Environment ID in environment name to update version in + "draft" environment. WARNING: this will negate all recent + changes to draft and can't be undone. You may want to save the + draft to a version before calling this function. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.UpdateEnvironmentRequest, dict]): + The request object. The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.v2beta1.Environments.UpdateEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.UpdateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.UpdateEnvironmentRequest): + request = environment.UpdateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment.name", request.environment.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_environment(self, + request: Union[environment.DeleteEnvironmentRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified agent environment. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.DeleteEnvironmentRequest, dict]): + The request object. The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.v2beta1.Environments.DeleteEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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. + # Minor optimization to avoid making a copy if the user passes + # in a environment.DeleteEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.DeleteEnvironmentRequest): + request = environment.DeleteEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_environment] + + # Certain 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 get_environment_history(self, + request: Union[environment.GetEnvironmentHistoryRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GetEnvironmentHistoryPager: + r"""Gets the history of the specified environment. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetEnvironmentHistoryRequest, dict]): + The request object. The request message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.services.environments.pagers.GetEnvironmentHistoryPager: + The response message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.GetEnvironmentHistoryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.GetEnvironmentHistoryRequest): + request = environment.GetEnvironmentHistoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_environment_history] + + # Certain 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.GetEnvironmentHistoryPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "EnvironmentsClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/pagers.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/pagers.py new file mode 100644 index 000000000..2882d6a04 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/pagers.py @@ -0,0 +1,262 @@ +# -*- 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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflow_v2beta1.types import environment + + +class ListEnvironmentsPager: + """A pager for iterating through ``list_environments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListEnvironmentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``environments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEnvironments`` requests and continue to iterate + through the ``environments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListEnvironmentsResponse` + 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[..., environment.ListEnvironmentsResponse], + request: environment.ListEnvironmentsRequest, + response: environment.ListEnvironmentsResponse, + *, + 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.dialogflow_v2beta1.types.ListEnvironmentsRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListEnvironmentsResponse): + 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 = environment.ListEnvironmentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[environment.ListEnvironmentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[environment.Environment]: + for page in self.pages: + yield from page.environments + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEnvironmentsAsyncPager: + """A pager for iterating through ``list_environments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListEnvironmentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``environments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEnvironments`` requests and continue to iterate + through the ``environments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListEnvironmentsResponse` + 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[environment.ListEnvironmentsResponse]], + request: environment.ListEnvironmentsRequest, + response: environment.ListEnvironmentsResponse, + *, + 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.dialogflow_v2beta1.types.ListEnvironmentsRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListEnvironmentsResponse): + 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 = environment.ListEnvironmentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[environment.ListEnvironmentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[environment.Environment]: + async def async_generator(): + async for page in self.pages: + for response in page.environments: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GetEnvironmentHistoryPager: + """A pager for iterating through ``get_environment_history`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.EnvironmentHistory` object, and + provides an ``__iter__`` method to iterate through its + ``entries`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GetEnvironmentHistory`` requests and continue to iterate + through the ``entries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.EnvironmentHistory` + 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[..., environment.EnvironmentHistory], + request: environment.GetEnvironmentHistoryRequest, + response: environment.EnvironmentHistory, + *, + 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.dialogflow_v2beta1.types.GetEnvironmentHistoryRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.EnvironmentHistory): + 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 = environment.GetEnvironmentHistoryRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[environment.EnvironmentHistory]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[environment.EnvironmentHistory.Entry]: + for page in self.pages: + yield from page.entries + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GetEnvironmentHistoryAsyncPager: + """A pager for iterating through ``get_environment_history`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.EnvironmentHistory` object, and + provides an ``__aiter__`` method to iterate through its + ``entries`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GetEnvironmentHistory`` requests and continue to iterate + through the ``entries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.EnvironmentHistory` + 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[environment.EnvironmentHistory]], + request: environment.GetEnvironmentHistoryRequest, + response: environment.EnvironmentHistory, + *, + 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.dialogflow_v2beta1.types.GetEnvironmentHistoryRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.EnvironmentHistory): + 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 = environment.GetEnvironmentHistoryRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[environment.EnvironmentHistory]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[environment.EnvironmentHistory.Entry]: + async def async_generator(): + async for page in self.pages: + for response in page.entries: + 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/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/__init__.py new file mode 100644 index 000000000..fac90efe0 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/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 EnvironmentsTransport +from .grpc import EnvironmentsGrpcTransport +from .grpc_asyncio import EnvironmentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[EnvironmentsTransport]] +_transport_registry['grpc'] = EnvironmentsGrpcTransport +_transport_registry['grpc_asyncio'] = EnvironmentsGrpcAsyncIOTransport + +__all__ = ( + 'EnvironmentsTransport', + 'EnvironmentsGrpcTransport', + 'EnvironmentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/base.py new file mode 100644 index 000000000..79290926f --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.types import environment +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-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class EnvironmentsTransport(abc.ABC): + """Abstract transport class for Environments.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_environments: gapic_v1.method.wrap_method( + self.list_environments, + default_timeout=None, + client_info=client_info, + ), + self.get_environment: gapic_v1.method.wrap_method( + self.get_environment, + default_timeout=None, + client_info=client_info, + ), + self.create_environment: gapic_v1.method.wrap_method( + self.create_environment, + default_timeout=None, + client_info=client_info, + ), + self.update_environment: gapic_v1.method.wrap_method( + self.update_environment, + default_timeout=None, + client_info=client_info, + ), + self.delete_environment: gapic_v1.method.wrap_method( + self.delete_environment, + default_timeout=None, + client_info=client_info, + ), + self.get_environment_history: gapic_v1.method.wrap_method( + self.get_environment_history, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_environments(self) -> Callable[ + [environment.ListEnvironmentsRequest], + Union[ + environment.ListEnvironmentsResponse, + Awaitable[environment.ListEnvironmentsResponse] + ]]: + raise NotImplementedError() + + @property + def get_environment(self) -> Callable[ + [environment.GetEnvironmentRequest], + Union[ + environment.Environment, + Awaitable[environment.Environment] + ]]: + raise NotImplementedError() + + @property + def create_environment(self) -> Callable[ + [environment.CreateEnvironmentRequest], + Union[ + environment.Environment, + Awaitable[environment.Environment] + ]]: + raise NotImplementedError() + + @property + def update_environment(self) -> Callable[ + [environment.UpdateEnvironmentRequest], + Union[ + environment.Environment, + Awaitable[environment.Environment] + ]]: + raise NotImplementedError() + + @property + def delete_environment(self) -> Callable[ + [environment.DeleteEnvironmentRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_environment_history(self) -> Callable[ + [environment.GetEnvironmentHistoryRequest], + Union[ + environment.EnvironmentHistory, + Awaitable[environment.EnvironmentHistory] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'EnvironmentsTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc.py new file mode 100644 index 000000000..4e1a2c1c9 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc.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 Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import environment +from google.protobuf import empty_pb2 # type: ignore +from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO + + +class EnvironmentsGrpcTransport(EnvironmentsTransport): + """gRPC backend transport for Environments. + + Service for managing + [Environments][google.cloud.dialogflow.v2beta1.Environment]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 = 'dialogflow.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 list_environments(self) -> Callable[ + [environment.ListEnvironmentsRequest], + environment.ListEnvironmentsResponse]: + r"""Return a callable for the list environments method over gRPC. + + Returns the list of all non-draft environments of the + specified agent. + + Returns: + Callable[[~.ListEnvironmentsRequest], + ~.ListEnvironmentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environments' not in self._stubs: + self._stubs['list_environments'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Environments/ListEnvironments', + request_serializer=environment.ListEnvironmentsRequest.serialize, + response_deserializer=environment.ListEnvironmentsResponse.deserialize, + ) + return self._stubs['list_environments'] + + @property + def get_environment(self) -> Callable[ + [environment.GetEnvironmentRequest], + environment.Environment]: + r"""Return a callable for the get environment method over gRPC. + + Retrieves the specified agent environment. + + Returns: + Callable[[~.GetEnvironmentRequest], + ~.Environment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environment' not in self._stubs: + self._stubs['get_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Environments/GetEnvironment', + request_serializer=environment.GetEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs['get_environment'] + + @property + def create_environment(self) -> Callable[ + [environment.CreateEnvironmentRequest], + environment.Environment]: + r"""Return a callable for the create environment method over gRPC. + + Creates an agent environment. + + Returns: + Callable[[~.CreateEnvironmentRequest], + ~.Environment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environment' not in self._stubs: + self._stubs['create_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Environments/CreateEnvironment', + request_serializer=environment.CreateEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs['create_environment'] + + @property + def update_environment(self) -> Callable[ + [environment.UpdateEnvironmentRequest], + environment.Environment]: + r"""Return a callable for the update environment method over gRPC. + + Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment keeps on serving the previous version + of the agent. After the new agent version is done loading, the + environment is set back to the ``RUNNING`` state. You can use + "-" as Environment ID in environment name to update version in + "draft" environment. WARNING: this will negate all recent + changes to draft and can't be undone. You may want to save the + draft to a version before calling this function. + + Returns: + Callable[[~.UpdateEnvironmentRequest], + ~.Environment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environment' not in self._stubs: + self._stubs['update_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Environments/UpdateEnvironment', + request_serializer=environment.UpdateEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs['update_environment'] + + @property + def delete_environment(self) -> Callable[ + [environment.DeleteEnvironmentRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete environment method over gRPC. + + Deletes the specified agent environment. + + Returns: + Callable[[~.DeleteEnvironmentRequest], + ~.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_environment' not in self._stubs: + self._stubs['delete_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Environments/DeleteEnvironment', + request_serializer=environment.DeleteEnvironmentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_environment'] + + @property + def get_environment_history(self) -> Callable[ + [environment.GetEnvironmentHistoryRequest], + environment.EnvironmentHistory]: + r"""Return a callable for the get environment history method over gRPC. + + Gets the history of the specified environment. + + Returns: + Callable[[~.GetEnvironmentHistoryRequest], + ~.EnvironmentHistory]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environment_history' not in self._stubs: + self._stubs['get_environment_history'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Environments/GetEnvironmentHistory', + request_serializer=environment.GetEnvironmentHistoryRequest.serialize, + response_deserializer=environment.EnvironmentHistory.deserialize, + ) + return self._stubs['get_environment_history'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'EnvironmentsGrpcTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc_asyncio.py new file mode 100644 index 000000000..ea70443fa --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc_asyncio.py @@ -0,0 +1,403 @@ +# -*- 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 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import environment +from google.protobuf import empty_pb2 # type: ignore +from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO +from .grpc import EnvironmentsGrpcTransport + + +class EnvironmentsGrpcAsyncIOTransport(EnvironmentsTransport): + """gRPC AsyncIO backend transport for Environments. + + Service for managing + [Environments][google.cloud.dialogflow.v2beta1.Environment]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 list_environments(self) -> Callable[ + [environment.ListEnvironmentsRequest], + Awaitable[environment.ListEnvironmentsResponse]]: + r"""Return a callable for the list environments method over gRPC. + + Returns the list of all non-draft environments of the + specified agent. + + Returns: + Callable[[~.ListEnvironmentsRequest], + Awaitable[~.ListEnvironmentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environments' not in self._stubs: + self._stubs['list_environments'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Environments/ListEnvironments', + request_serializer=environment.ListEnvironmentsRequest.serialize, + response_deserializer=environment.ListEnvironmentsResponse.deserialize, + ) + return self._stubs['list_environments'] + + @property + def get_environment(self) -> Callable[ + [environment.GetEnvironmentRequest], + Awaitable[environment.Environment]]: + r"""Return a callable for the get environment method over gRPC. + + Retrieves the specified agent environment. + + Returns: + Callable[[~.GetEnvironmentRequest], + Awaitable[~.Environment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environment' not in self._stubs: + self._stubs['get_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Environments/GetEnvironment', + request_serializer=environment.GetEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs['get_environment'] + + @property + def create_environment(self) -> Callable[ + [environment.CreateEnvironmentRequest], + Awaitable[environment.Environment]]: + r"""Return a callable for the create environment method over gRPC. + + Creates an agent environment. + + Returns: + Callable[[~.CreateEnvironmentRequest], + Awaitable[~.Environment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environment' not in self._stubs: + self._stubs['create_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Environments/CreateEnvironment', + request_serializer=environment.CreateEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs['create_environment'] + + @property + def update_environment(self) -> Callable[ + [environment.UpdateEnvironmentRequest], + Awaitable[environment.Environment]]: + r"""Return a callable for the update environment method over gRPC. + + Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment keeps on serving the previous version + of the agent. After the new agent version is done loading, the + environment is set back to the ``RUNNING`` state. You can use + "-" as Environment ID in environment name to update version in + "draft" environment. WARNING: this will negate all recent + changes to draft and can't be undone. You may want to save the + draft to a version before calling this function. + + Returns: + Callable[[~.UpdateEnvironmentRequest], + Awaitable[~.Environment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environment' not in self._stubs: + self._stubs['update_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Environments/UpdateEnvironment', + request_serializer=environment.UpdateEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs['update_environment'] + + @property + def delete_environment(self) -> Callable[ + [environment.DeleteEnvironmentRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete environment method over gRPC. + + Deletes the specified agent environment. + + Returns: + Callable[[~.DeleteEnvironmentRequest], + 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_environment' not in self._stubs: + self._stubs['delete_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Environments/DeleteEnvironment', + request_serializer=environment.DeleteEnvironmentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_environment'] + + @property + def get_environment_history(self) -> Callable[ + [environment.GetEnvironmentHistoryRequest], + Awaitable[environment.EnvironmentHistory]]: + r"""Return a callable for the get environment history method over gRPC. + + Gets the history of the specified environment. + + Returns: + Callable[[~.GetEnvironmentHistoryRequest], + Awaitable[~.EnvironmentHistory]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environment_history' not in self._stubs: + self._stubs['get_environment_history'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Environments/GetEnvironmentHistory', + request_serializer=environment.GetEnvironmentHistoryRequest.serialize, + response_deserializer=environment.EnvironmentHistory.deserialize, + ) + return self._stubs['get_environment_history'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'EnvironmentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/__init__.py new file mode 100644 index 000000000..95fd359ef --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/__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 FulfillmentsClient +from .async_client import FulfillmentsAsyncClient + +__all__ = ( + 'FulfillmentsClient', + 'FulfillmentsAsyncClient', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/async_client.py new file mode 100644 index 000000000..0bbeba9d3 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/async_client.py @@ -0,0 +1,355 @@ +# -*- 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 + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2beta1.types import fulfillment +from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import FulfillmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import FulfillmentsGrpcAsyncIOTransport +from .client import FulfillmentsClient + + +class FulfillmentsAsyncClient: + """Service for managing + [Fulfillments][google.cloud.dialogflow.v2beta1.Fulfillment]. + """ + + _client: FulfillmentsClient + + DEFAULT_ENDPOINT = FulfillmentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = FulfillmentsClient.DEFAULT_MTLS_ENDPOINT + + fulfillment_path = staticmethod(FulfillmentsClient.fulfillment_path) + parse_fulfillment_path = staticmethod(FulfillmentsClient.parse_fulfillment_path) + common_billing_account_path = staticmethod(FulfillmentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(FulfillmentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(FulfillmentsClient.common_folder_path) + parse_common_folder_path = staticmethod(FulfillmentsClient.parse_common_folder_path) + common_organization_path = staticmethod(FulfillmentsClient.common_organization_path) + parse_common_organization_path = staticmethod(FulfillmentsClient.parse_common_organization_path) + common_project_path = staticmethod(FulfillmentsClient.common_project_path) + parse_common_project_path = staticmethod(FulfillmentsClient.parse_common_project_path) + common_location_path = staticmethod(FulfillmentsClient.common_location_path) + parse_common_location_path = staticmethod(FulfillmentsClient.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: + FulfillmentsAsyncClient: The constructed client. + """ + return FulfillmentsClient.from_service_account_info.__func__(FulfillmentsAsyncClient, 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: + FulfillmentsAsyncClient: The constructed client. + """ + return FulfillmentsClient.from_service_account_file.__func__(FulfillmentsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> FulfillmentsTransport: + """Returns the transport used by the client instance. + + Returns: + FulfillmentsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(FulfillmentsClient).get_transport_class, type(FulfillmentsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, FulfillmentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the fulfillments 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, ~.FulfillmentsTransport]): 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 = FulfillmentsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_fulfillment(self, + request: Union[fulfillment.GetFulfillmentRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> fulfillment.Fulfillment: + r"""Retrieves the fulfillment. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetFulfillmentRequest, dict]): + The request object. The request message for + [Fulfillments.GetFulfillment][google.cloud.dialogflow.v2beta1.Fulfillments.GetFulfillment]. + name (:class:`str`): + Required. The name of the fulfillment. Supported + formats: + + - ``projects//agent/fulfillment`` + - ``projects//locations//agent/fulfillment`` + + 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.dialogflow_v2beta1.types.Fulfillment: + By default, your agent responds to a matched intent with a static response. + As an alternative, you can provide a more dynamic + response by using fulfillment. When you enable + fulfillment for an intent, Dialogflow responds to + that intent by calling a service that you define. For + example, if an end-user wants to schedule a haircut + on Friday, your service can check your database and + respond to the end-user with availability information + for Friday. + + For more information, see the [fulfillment + guide](\ https://cloud.google.com/dialogflow/docs/fulfillment-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = fulfillment.GetFulfillmentRequest(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_fulfillment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_fulfillment(self, + request: Union[gcd_fulfillment.UpdateFulfillmentRequest, dict] = None, + *, + fulfillment: gcd_fulfillment.Fulfillment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_fulfillment.Fulfillment: + r"""Updates the fulfillment. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.UpdateFulfillmentRequest, dict]): + The request object. The request message for + [Fulfillments.UpdateFulfillment][google.cloud.dialogflow.v2beta1.Fulfillments.UpdateFulfillment]. + fulfillment (:class:`google.cloud.dialogflow_v2beta1.types.Fulfillment`): + Required. The fulfillment to update. + This corresponds to the ``fulfillment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The mask to control which + fields get updated. If the mask is not + present, all fields will be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Fulfillment: + By default, your agent responds to a matched intent with a static response. + As an alternative, you can provide a more dynamic + response by using fulfillment. When you enable + fulfillment for an intent, Dialogflow responds to + that intent by calling a service that you define. For + example, if an end-user wants to schedule a haircut + on Friday, your service can check your database and + respond to the end-user with availability information + for Friday. + + For more information, see the [fulfillment + guide](\ https://cloud.google.com/dialogflow/docs/fulfillment-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([fulfillment, 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 = gcd_fulfillment.UpdateFulfillmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if fulfillment is not None: + request.fulfillment = fulfillment + 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_fulfillment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("fulfillment.name", request.fulfillment.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "FulfillmentsAsyncClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/client.py new file mode 100644 index 000000000..e16251ec0 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/client.py @@ -0,0 +1,553 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2beta1.types import fulfillment +from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import FulfillmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import FulfillmentsGrpcTransport +from .transports.grpc_asyncio import FulfillmentsGrpcAsyncIOTransport + + +class FulfillmentsClientMeta(type): + """Metaclass for the Fulfillments 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[FulfillmentsTransport]] + _transport_registry["grpc"] = FulfillmentsGrpcTransport + _transport_registry["grpc_asyncio"] = FulfillmentsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[FulfillmentsTransport]: + """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 FulfillmentsClient(metaclass=FulfillmentsClientMeta): + """Service for managing + [Fulfillments][google.cloud.dialogflow.v2beta1.Fulfillment]. + """ + + @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 = "dialogflow.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: + FulfillmentsClient: 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: + FulfillmentsClient: 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) -> FulfillmentsTransport: + """Returns the transport used by the client instance. + + Returns: + FulfillmentsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def fulfillment_path(project: str,) -> str: + """Returns a fully-qualified fulfillment string.""" + return "projects/{project}/agent/fulfillment".format(project=project, ) + + @staticmethod + def parse_fulfillment_path(path: str) -> Dict[str,str]: + """Parses a fulfillment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/fulfillment$", 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, FulfillmentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the fulfillments 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, FulfillmentsTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, FulfillmentsTransport): + # transport is a FulfillmentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def get_fulfillment(self, + request: Union[fulfillment.GetFulfillmentRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> fulfillment.Fulfillment: + r"""Retrieves the fulfillment. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetFulfillmentRequest, dict]): + The request object. The request message for + [Fulfillments.GetFulfillment][google.cloud.dialogflow.v2beta1.Fulfillments.GetFulfillment]. + name (str): + Required. The name of the fulfillment. Supported + formats: + + - ``projects//agent/fulfillment`` + - ``projects//locations//agent/fulfillment`` + + 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.dialogflow_v2beta1.types.Fulfillment: + By default, your agent responds to a matched intent with a static response. + As an alternative, you can provide a more dynamic + response by using fulfillment. When you enable + fulfillment for an intent, Dialogflow responds to + that intent by calling a service that you define. For + example, if an end-user wants to schedule a haircut + on Friday, your service can check your database and + respond to the end-user with availability information + for Friday. + + For more information, see the [fulfillment + guide](\ https://cloud.google.com/dialogflow/docs/fulfillment-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a fulfillment.GetFulfillmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, fulfillment.GetFulfillmentRequest): + request = fulfillment.GetFulfillmentRequest(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_fulfillment] + + # Certain 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 update_fulfillment(self, + request: Union[gcd_fulfillment.UpdateFulfillmentRequest, dict] = None, + *, + fulfillment: gcd_fulfillment.Fulfillment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_fulfillment.Fulfillment: + r"""Updates the fulfillment. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.UpdateFulfillmentRequest, dict]): + The request object. The request message for + [Fulfillments.UpdateFulfillment][google.cloud.dialogflow.v2beta1.Fulfillments.UpdateFulfillment]. + fulfillment (google.cloud.dialogflow_v2beta1.types.Fulfillment): + Required. The fulfillment to update. + This corresponds to the ``fulfillment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which + fields get updated. If the mask is not + present, all fields will be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Fulfillment: + By default, your agent responds to a matched intent with a static response. + As an alternative, you can provide a more dynamic + response by using fulfillment. When you enable + fulfillment for an intent, Dialogflow responds to + that intent by calling a service that you define. For + example, if an end-user wants to schedule a haircut + on Friday, your service can check your database and + respond to the end-user with availability information + for Friday. + + For more information, see the [fulfillment + guide](\ https://cloud.google.com/dialogflow/docs/fulfillment-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([fulfillment, 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 gcd_fulfillment.UpdateFulfillmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_fulfillment.UpdateFulfillmentRequest): + request = gcd_fulfillment.UpdateFulfillmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if fulfillment is not None: + request.fulfillment = fulfillment + 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_fulfillment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("fulfillment.name", request.fulfillment.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "FulfillmentsClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/__init__.py new file mode 100644 index 000000000..4b41f9212 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/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 FulfillmentsTransport +from .grpc import FulfillmentsGrpcTransport +from .grpc_asyncio import FulfillmentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[FulfillmentsTransport]] +_transport_registry['grpc'] = FulfillmentsGrpcTransport +_transport_registry['grpc_asyncio'] = FulfillmentsGrpcAsyncIOTransport + +__all__ = ( + 'FulfillmentsTransport', + 'FulfillmentsGrpcTransport', + 'FulfillmentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/base.py new file mode 100644 index 000000000..c584f3497 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/base.py @@ -0,0 +1,162 @@ +# -*- 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.types import fulfillment +from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class FulfillmentsTransport(abc.ABC): + """Abstract transport class for Fulfillments.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_fulfillment: gapic_v1.method.wrap_method( + self.get_fulfillment, + default_timeout=None, + client_info=client_info, + ), + self.update_fulfillment: gapic_v1.method.wrap_method( + self.update_fulfillment, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def get_fulfillment(self) -> Callable[ + [fulfillment.GetFulfillmentRequest], + Union[ + fulfillment.Fulfillment, + Awaitable[fulfillment.Fulfillment] + ]]: + raise NotImplementedError() + + @property + def update_fulfillment(self) -> Callable[ + [gcd_fulfillment.UpdateFulfillmentRequest], + Union[ + gcd_fulfillment.Fulfillment, + Awaitable[gcd_fulfillment.Fulfillment] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'FulfillmentsTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc.py new file mode 100644 index 000000000..c3529d36f --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc.py @@ -0,0 +1,282 @@ +# -*- 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 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import fulfillment +from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment +from .base import FulfillmentsTransport, DEFAULT_CLIENT_INFO + + +class FulfillmentsGrpcTransport(FulfillmentsTransport): + """gRPC backend transport for Fulfillments. + + Service for managing + [Fulfillments][google.cloud.dialogflow.v2beta1.Fulfillment]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def get_fulfillment(self) -> Callable[ + [fulfillment.GetFulfillmentRequest], + fulfillment.Fulfillment]: + r"""Return a callable for the get fulfillment method over gRPC. + + Retrieves the fulfillment. + + Returns: + Callable[[~.GetFulfillmentRequest], + ~.Fulfillment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_fulfillment' not in self._stubs: + self._stubs['get_fulfillment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Fulfillments/GetFulfillment', + request_serializer=fulfillment.GetFulfillmentRequest.serialize, + response_deserializer=fulfillment.Fulfillment.deserialize, + ) + return self._stubs['get_fulfillment'] + + @property + def update_fulfillment(self) -> Callable[ + [gcd_fulfillment.UpdateFulfillmentRequest], + gcd_fulfillment.Fulfillment]: + r"""Return a callable for the update fulfillment method over gRPC. + + Updates the fulfillment. + + Returns: + Callable[[~.UpdateFulfillmentRequest], + ~.Fulfillment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_fulfillment' not in self._stubs: + self._stubs['update_fulfillment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Fulfillments/UpdateFulfillment', + request_serializer=gcd_fulfillment.UpdateFulfillmentRequest.serialize, + response_deserializer=gcd_fulfillment.Fulfillment.deserialize, + ) + return self._stubs['update_fulfillment'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'FulfillmentsGrpcTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc_asyncio.py new file mode 100644 index 000000000..edd349a7b --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc_asyncio.py @@ -0,0 +1,286 @@ +# -*- 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 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import fulfillment +from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment +from .base import FulfillmentsTransport, DEFAULT_CLIENT_INFO +from .grpc import FulfillmentsGrpcTransport + + +class FulfillmentsGrpcAsyncIOTransport(FulfillmentsTransport): + """gRPC AsyncIO backend transport for Fulfillments. + + Service for managing + [Fulfillments][google.cloud.dialogflow.v2beta1.Fulfillment]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def get_fulfillment(self) -> Callable[ + [fulfillment.GetFulfillmentRequest], + Awaitable[fulfillment.Fulfillment]]: + r"""Return a callable for the get fulfillment method over gRPC. + + Retrieves the fulfillment. + + Returns: + Callable[[~.GetFulfillmentRequest], + Awaitable[~.Fulfillment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_fulfillment' not in self._stubs: + self._stubs['get_fulfillment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Fulfillments/GetFulfillment', + request_serializer=fulfillment.GetFulfillmentRequest.serialize, + response_deserializer=fulfillment.Fulfillment.deserialize, + ) + return self._stubs['get_fulfillment'] + + @property + def update_fulfillment(self) -> Callable[ + [gcd_fulfillment.UpdateFulfillmentRequest], + Awaitable[gcd_fulfillment.Fulfillment]]: + r"""Return a callable for the update fulfillment method over gRPC. + + Updates the fulfillment. + + Returns: + Callable[[~.UpdateFulfillmentRequest], + Awaitable[~.Fulfillment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_fulfillment' not in self._stubs: + self._stubs['update_fulfillment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Fulfillments/UpdateFulfillment', + request_serializer=gcd_fulfillment.UpdateFulfillmentRequest.serialize, + response_deserializer=gcd_fulfillment.Fulfillment.deserialize, + ) + return self._stubs['update_fulfillment'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'FulfillmentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/__init__.py new file mode 100644 index 000000000..8204500fb --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/__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 IntentsClient +from .async_client import IntentsAsyncClient + +__all__ = ( + 'IntentsClient', + 'IntentsAsyncClient', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/async_client.py new file mode 100644 index 000000000..8524f9f50 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/async_client.py @@ -0,0 +1,939 @@ +# -*- 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 + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.dialogflow_v2beta1.services.intents import pagers +from google.cloud.dialogflow_v2beta1.types import context +from google.cloud.dialogflow_v2beta1.types import intent +from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import IntentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import IntentsGrpcAsyncIOTransport +from .client import IntentsClient + + +class IntentsAsyncClient: + """Service for managing + [Intents][google.cloud.dialogflow.v2beta1.Intent]. + """ + + _client: IntentsClient + + DEFAULT_ENDPOINT = IntentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = IntentsClient.DEFAULT_MTLS_ENDPOINT + + context_path = staticmethod(IntentsClient.context_path) + parse_context_path = staticmethod(IntentsClient.parse_context_path) + intent_path = staticmethod(IntentsClient.intent_path) + parse_intent_path = staticmethod(IntentsClient.parse_intent_path) + common_billing_account_path = staticmethod(IntentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(IntentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(IntentsClient.common_folder_path) + parse_common_folder_path = staticmethod(IntentsClient.parse_common_folder_path) + common_organization_path = staticmethod(IntentsClient.common_organization_path) + parse_common_organization_path = staticmethod(IntentsClient.parse_common_organization_path) + common_project_path = staticmethod(IntentsClient.common_project_path) + parse_common_project_path = staticmethod(IntentsClient.parse_common_project_path) + common_location_path = staticmethod(IntentsClient.common_location_path) + parse_common_location_path = staticmethod(IntentsClient.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: + IntentsAsyncClient: The constructed client. + """ + return IntentsClient.from_service_account_info.__func__(IntentsAsyncClient, 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: + IntentsAsyncClient: The constructed client. + """ + return IntentsClient.from_service_account_file.__func__(IntentsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> IntentsTransport: + """Returns the transport used by the client instance. + + Returns: + IntentsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(IntentsClient).get_transport_class, type(IntentsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, IntentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the intents 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, ~.IntentsTransport]): 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 = IntentsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_intents(self, + request: Union[intent.ListIntentsRequest, dict] = None, + *, + parent: str = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListIntentsAsyncPager: + r"""Returns the list of all intents in the specified + agent. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListIntentsRequest, dict]): + The request object. The request message for + [Intents.ListIntents][google.cloud.dialogflow.v2beta1.Intents.ListIntents]. + parent (:class:`str`): + Required. The agent to list all intents from. Format: + ``projects//agent`` or + ``projects//locations//agent``. + + Alternatively, you can specify the environment to list + intents for. Format: + ``projects//agent/environments/`` + or + ``projects//locations//agent/environments/``. + Note: training phrases of the intents will not be + returned for non-draft environment. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (:class:`str`): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.services.intents.pagers.ListIntentsAsyncPager: + The response message for + [Intents.ListIntents][google.cloud.dialogflow.v2beta1.Intents.ListIntents]. + + 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, language_code]) + if request is 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 = intent.ListIntentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if language_code is not None: + request.language_code = language_code + + # 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_intents, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListIntentsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_intent(self, + request: Union[intent.GetIntentRequest, dict] = None, + *, + name: str = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> intent.Intent: + r"""Retrieves the specified intent. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetIntentRequest, dict]): + The request object. The request message for + [Intents.GetIntent][google.cloud.dialogflow.v2beta1.Intents.GetIntent]. + name (:class:`str`): + Required. The name of the intent. Supported formats: + + - ``projects//agent/intents/`` + - ``projects//locations//agent/intents/`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (:class:`str`): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Intent: + An intent categorizes an end-user's intention for one conversation turn. For + each agent, you define many intents, where your + combined intents can handle a complete conversation. + When an end-user writes or says something, referred + to as an end-user expression or end-user input, + Dialogflow matches the end-user input to the best + intent in your agent. Matching an intent is also + known as intent classification. + + For more information, see the [intent + guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, language_code]) + if request is 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 = intent.GetIntentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if language_code is not None: + request.language_code = language_code + + # 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_intent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_intent(self, + request: Union[gcd_intent.CreateIntentRequest, dict] = None, + *, + parent: str = None, + intent: gcd_intent.Intent = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_intent.Intent: + r"""Creates an intent in the specified agent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.CreateIntentRequest, dict]): + The request object. The request message for + [Intents.CreateIntent][google.cloud.dialogflow.v2beta1.Intents.CreateIntent]. + parent (:class:`str`): + Required. The agent to create a intent for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + intent (:class:`google.cloud.dialogflow_v2beta1.types.Intent`): + Required. The intent to create. + This corresponds to the ``intent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (:class:`str`): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Intent: + An intent categorizes an end-user's intention for one conversation turn. For + each agent, you define many intents, where your + combined intents can handle a complete conversation. + When an end-user writes or says something, referred + to as an end-user expression or end-user input, + Dialogflow matches the end-user input to the best + intent in your agent. Matching an intent is also + known as intent classification. + + For more information, see the [intent + guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, intent, language_code]) + if request is 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 = gcd_intent.CreateIntentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if intent is not None: + request.intent = intent + if language_code is not None: + request.language_code = language_code + + # 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_intent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_intent(self, + request: Union[gcd_intent.UpdateIntentRequest, dict] = None, + *, + intent: gcd_intent.Intent = None, + update_mask: field_mask_pb2.FieldMask = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_intent.Intent: + r"""Updates the specified intent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.UpdateIntentRequest, dict]): + The request object. The request message for + [Intents.UpdateIntent][google.cloud.dialogflow.v2beta1.Intents.UpdateIntent]. + intent (:class:`google.cloud.dialogflow_v2beta1.types.Intent`): + Required. The intent to update. + This corresponds to the ``intent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (:class:`str`): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Intent: + An intent categorizes an end-user's intention for one conversation turn. For + each agent, you define many intents, where your + combined intents can handle a complete conversation. + When an end-user writes or says something, referred + to as an end-user expression or end-user input, + Dialogflow matches the end-user input to the best + intent in your agent. Matching an intent is also + known as intent classification. + + For more information, see the [intent + guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([intent, update_mask, language_code]) + if request is 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 = gcd_intent.UpdateIntentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if intent is not None: + request.intent = intent + if update_mask is not None: + request.update_mask = update_mask + if language_code is not None: + request.language_code = language_code + + # 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_intent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("intent.name", request.intent.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_intent(self, + request: Union[intent.DeleteIntentRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified intent and its direct or indirect followup + intents. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.DeleteIntentRequest, dict]): + The request object. The request message for + [Intents.DeleteIntent][google.cloud.dialogflow.v2beta1.Intents.DeleteIntent]. + name (:class:`str`): + Required. The name of the intent to delete. If this + intent has direct or indirect followup intents, we also + delete them. + + Supported formats: + + - ``projects//agent/intents/`` + - ``projects//locations//agent/intents/`` + + 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 = intent.DeleteIntentRequest(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_intent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def batch_update_intents(self, + request: Union[intent.BatchUpdateIntentsRequest, dict] = None, + *, + parent: str = None, + intent_batch_uri: str = None, + intent_batch_inline: intent.IntentBatch = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates/Creates multiple intents in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [BatchUpdateIntentsResponse][google.cloud.dialogflow.v2beta1.BatchUpdateIntentsResponse] + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.BatchUpdateIntentsRequest, dict]): + The request object. The request message for + [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2beta1.Intents.BatchUpdateIntents]. + parent (:class:`str`): + Required. The name of the agent to update or create + intents in. Supported formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + intent_batch_uri (:class:`str`): + The URI to a Google Cloud Storage + file containing intents to update or + create. The file format can either be a + serialized proto (of IntentBatch type) + or JSON object. Note: The URI must start + with "gs://". + + This corresponds to the ``intent_batch_uri`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + intent_batch_inline (:class:`google.cloud.dialogflow_v2beta1.types.IntentBatch`): + The collection of intents to update + or create. + + This corresponds to the ``intent_batch_inline`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.dialogflow_v2beta1.types.BatchUpdateIntentsResponse` + The response message for + [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2beta1.Intents.BatchUpdateIntents]. + + """ + # 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, intent_batch_uri, intent_batch_inline]) + if request is 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 = intent.BatchUpdateIntentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if intent_batch_uri is not None: + request.intent_batch_uri = intent_batch_uri + if intent_batch_inline is not None: + request.intent_batch_inline = intent_batch_inline + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_update_intents, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + intent.BatchUpdateIntentsResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def batch_delete_intents(self, + request: Union[intent.BatchDeleteIntentsRequest, dict] = None, + *, + parent: str = None, + intents: Sequence[intent.Intent] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes intents in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.BatchDeleteIntentsRequest, dict]): + The request object. The request message for + [Intents.BatchDeleteIntents][google.cloud.dialogflow.v2beta1.Intents.BatchDeleteIntents]. + parent (:class:`str`): + Required. The name of the agent to delete all entities + types for. Supported formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + intents (:class:`Sequence[google.cloud.dialogflow_v2beta1.types.Intent]`): + Required. The collection of intents to delete. Only + intent ``name`` must be filled in. + + This corresponds to the ``intents`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, intents]) + if request is 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 = intent.BatchDeleteIntentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if intents: + request.intents.extend(intents) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_delete_intents, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "IntentsAsyncClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/client.py new file mode 100644 index 000000000..7ef278957 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/client.py @@ -0,0 +1,1146 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.dialogflow_v2beta1.services.intents import pagers +from google.cloud.dialogflow_v2beta1.types import context +from google.cloud.dialogflow_v2beta1.types import intent +from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import IntentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import IntentsGrpcTransport +from .transports.grpc_asyncio import IntentsGrpcAsyncIOTransport + + +class IntentsClientMeta(type): + """Metaclass for the Intents 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[IntentsTransport]] + _transport_registry["grpc"] = IntentsGrpcTransport + _transport_registry["grpc_asyncio"] = IntentsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[IntentsTransport]: + """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 IntentsClient(metaclass=IntentsClientMeta): + """Service for managing + [Intents][google.cloud.dialogflow.v2beta1.Intent]. + """ + + @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 = "dialogflow.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: + IntentsClient: 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: + IntentsClient: 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) -> IntentsTransport: + """Returns the transport used by the client instance. + + Returns: + IntentsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def context_path(project: str,session: str,context: str,) -> str: + """Returns a fully-qualified context string.""" + return "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) + + @staticmethod + def parse_context_path(path: str) -> Dict[str,str]: + """Parses a context path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/contexts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def intent_path(project: str,intent: str,) -> str: + """Returns a fully-qualified intent string.""" + return "projects/{project}/agent/intents/{intent}".format(project=project, intent=intent, ) + + @staticmethod + def parse_intent_path(path: str) -> Dict[str,str]: + """Parses a intent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/intents/(?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, IntentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the intents 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, IntentsTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, IntentsTransport): + # transport is a IntentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_intents(self, + request: Union[intent.ListIntentsRequest, dict] = None, + *, + parent: str = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListIntentsPager: + r"""Returns the list of all intents in the specified + agent. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListIntentsRequest, dict]): + The request object. The request message for + [Intents.ListIntents][google.cloud.dialogflow.v2beta1.Intents.ListIntents]. + parent (str): + Required. The agent to list all intents from. Format: + ``projects//agent`` or + ``projects//locations//agent``. + + Alternatively, you can specify the environment to list + intents for. Format: + ``projects//agent/environments/`` + or + ``projects//locations//agent/environments/``. + Note: training phrases of the intents will not be + returned for non-draft environment. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.services.intents.pagers.ListIntentsPager: + The response message for + [Intents.ListIntents][google.cloud.dialogflow.v2beta1.Intents.ListIntents]. + + 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, language_code]) + if request is 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 intent.ListIntentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, intent.ListIntentsRequest): + request = intent.ListIntentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if language_code is not None: + request.language_code = language_code + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_intents] + + # Certain 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.ListIntentsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_intent(self, + request: Union[intent.GetIntentRequest, dict] = None, + *, + name: str = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> intent.Intent: + r"""Retrieves the specified intent. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetIntentRequest, dict]): + The request object. The request message for + [Intents.GetIntent][google.cloud.dialogflow.v2beta1.Intents.GetIntent]. + name (str): + Required. The name of the intent. Supported formats: + + - ``projects//agent/intents/`` + - ``projects//locations//agent/intents/`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Intent: + An intent categorizes an end-user's intention for one conversation turn. For + each agent, you define many intents, where your + combined intents can handle a complete conversation. + When an end-user writes or says something, referred + to as an end-user expression or end-user input, + Dialogflow matches the end-user input to the best + intent in your agent. Matching an intent is also + known as intent classification. + + For more information, see the [intent + guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, language_code]) + if request is 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 intent.GetIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, intent.GetIntentRequest): + request = intent.GetIntentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if language_code is not None: + request.language_code = language_code + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_intent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_intent(self, + request: Union[gcd_intent.CreateIntentRequest, dict] = None, + *, + parent: str = None, + intent: gcd_intent.Intent = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_intent.Intent: + r"""Creates an intent in the specified agent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.CreateIntentRequest, dict]): + The request object. The request message for + [Intents.CreateIntent][google.cloud.dialogflow.v2beta1.Intents.CreateIntent]. + parent (str): + Required. The agent to create a intent for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + intent (google.cloud.dialogflow_v2beta1.types.Intent): + Required. The intent to create. + This corresponds to the ``intent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Intent: + An intent categorizes an end-user's intention for one conversation turn. For + each agent, you define many intents, where your + combined intents can handle a complete conversation. + When an end-user writes or says something, referred + to as an end-user expression or end-user input, + Dialogflow matches the end-user input to the best + intent in your agent. Matching an intent is also + known as intent classification. + + For more information, see the [intent + guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, intent, language_code]) + if request is 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 gcd_intent.CreateIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_intent.CreateIntentRequest): + request = gcd_intent.CreateIntentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if intent is not None: + request.intent = intent + if language_code is not None: + request.language_code = language_code + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_intent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_intent(self, + request: Union[gcd_intent.UpdateIntentRequest, dict] = None, + *, + intent: gcd_intent.Intent = None, + update_mask: field_mask_pb2.FieldMask = None, + language_code: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_intent.Intent: + r"""Updates the specified intent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.UpdateIntentRequest, dict]): + The request object. The request message for + [Intents.UpdateIntent][google.cloud.dialogflow.v2beta1.Intents.UpdateIntent]. + intent (google.cloud.dialogflow_v2beta1.types.Intent): + Required. The intent to update. + This corresponds to the ``intent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + + This corresponds to the ``language_code`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Intent: + An intent categorizes an end-user's intention for one conversation turn. For + each agent, you define many intents, where your + combined intents can handle a complete conversation. + When an end-user writes or says something, referred + to as an end-user expression or end-user input, + Dialogflow matches the end-user input to the best + intent in your agent. Matching an intent is also + known as intent classification. + + For more information, see the [intent + guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([intent, update_mask, language_code]) + if request is 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 gcd_intent.UpdateIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_intent.UpdateIntentRequest): + request = gcd_intent.UpdateIntentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if intent is not None: + request.intent = intent + if update_mask is not None: + request.update_mask = update_mask + if language_code is not None: + request.language_code = language_code + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_intent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("intent.name", request.intent.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_intent(self, + request: Union[intent.DeleteIntentRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified intent and its direct or indirect followup + intents. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.DeleteIntentRequest, dict]): + The request object. The request message for + [Intents.DeleteIntent][google.cloud.dialogflow.v2beta1.Intents.DeleteIntent]. + name (str): + Required. The name of the intent to delete. If this + intent has direct or indirect followup intents, we also + delete them. + + Supported formats: + + - ``projects//agent/intents/`` + - ``projects//locations//agent/intents/`` + + 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 intent.DeleteIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, intent.DeleteIntentRequest): + request = intent.DeleteIntentRequest(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_intent] + + # Certain 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 batch_update_intents(self, + request: Union[intent.BatchUpdateIntentsRequest, dict] = None, + *, + parent: str = None, + intent_batch_uri: str = None, + intent_batch_inline: intent.IntentBatch = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates/Creates multiple intents in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [BatchUpdateIntentsResponse][google.cloud.dialogflow.v2beta1.BatchUpdateIntentsResponse] + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.BatchUpdateIntentsRequest, dict]): + The request object. The request message for + [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2beta1.Intents.BatchUpdateIntents]. + parent (str): + Required. The name of the agent to update or create + intents in. Supported formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + intent_batch_uri (str): + The URI to a Google Cloud Storage + file containing intents to update or + create. The file format can either be a + serialized proto (of IntentBatch type) + or JSON object. Note: The URI must start + with "gs://". + + This corresponds to the ``intent_batch_uri`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + intent_batch_inline (google.cloud.dialogflow_v2beta1.types.IntentBatch): + The collection of intents to update + or create. + + This corresponds to the ``intent_batch_inline`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout 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.dialogflow_v2beta1.types.BatchUpdateIntentsResponse` + The response message for + [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2beta1.Intents.BatchUpdateIntents]. + + """ + # 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, intent_batch_uri, intent_batch_inline]) + if request is 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 intent.BatchUpdateIntentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, intent.BatchUpdateIntentsRequest): + request = intent.BatchUpdateIntentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if intent_batch_uri is not None: + request.intent_batch_uri = intent_batch_uri + if intent_batch_inline is not None: + request.intent_batch_inline = intent_batch_inline + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_update_intents] + + # Certain 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, + intent.BatchUpdateIntentsResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def batch_delete_intents(self, + request: Union[intent.BatchDeleteIntentsRequest, dict] = None, + *, + parent: str = None, + intents: Sequence[intent.Intent] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes intents in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.BatchDeleteIntentsRequest, dict]): + The request object. The request message for + [Intents.BatchDeleteIntents][google.cloud.dialogflow.v2beta1.Intents.BatchDeleteIntents]. + parent (str): + Required. The name of the agent to delete all entities + types for. Supported formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + intents (Sequence[google.cloud.dialogflow_v2beta1.types.Intent]): + Required. The collection of intents to delete. Only + intent ``name`` must be filled in. + + This corresponds to the ``intents`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, intents]) + if request is 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 intent.BatchDeleteIntentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, intent.BatchDeleteIntentsRequest): + request = intent.BatchDeleteIntentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if intents is not None: + request.intents = intents + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_delete_intents] + + # Certain 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, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "IntentsClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/pagers.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/pagers.py new file mode 100644 index 000000000..3762c1beb --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflow_v2beta1.types import intent + + +class ListIntentsPager: + """A pager for iterating through ``list_intents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListIntentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``intents`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListIntents`` requests and continue to iterate + through the ``intents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListIntentsResponse` + 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[..., intent.ListIntentsResponse], + request: intent.ListIntentsRequest, + response: intent.ListIntentsResponse, + *, + 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.dialogflow_v2beta1.types.ListIntentsRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListIntentsResponse): + 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 = intent.ListIntentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[intent.ListIntentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[intent.Intent]: + for page in self.pages: + yield from page.intents + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListIntentsAsyncPager: + """A pager for iterating through ``list_intents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListIntentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``intents`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListIntents`` requests and continue to iterate + through the ``intents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListIntentsResponse` + 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[intent.ListIntentsResponse]], + request: intent.ListIntentsRequest, + response: intent.ListIntentsResponse, + *, + 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.dialogflow_v2beta1.types.ListIntentsRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListIntentsResponse): + 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 = intent.ListIntentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[intent.ListIntentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[intent.Intent]: + async def async_generator(): + async for page in self.pages: + for response in page.intents: + 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/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/__init__.py new file mode 100644 index 000000000..aa8039bba --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/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 IntentsTransport +from .grpc import IntentsGrpcTransport +from .grpc_asyncio import IntentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[IntentsTransport]] +_transport_registry['grpc'] = IntentsGrpcTransport +_transport_registry['grpc_asyncio'] = IntentsGrpcAsyncIOTransport + +__all__ = ( + 'IntentsTransport', + 'IntentsGrpcTransport', + 'IntentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/base.py new file mode 100644 index 000000000..97825551f --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/base.py @@ -0,0 +1,240 @@ +# -*- 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.types import intent +from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent +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-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class IntentsTransport(abc.ABC): + """Abstract transport class for Intents.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_intents: gapic_v1.method.wrap_method( + self.list_intents, + default_timeout=None, + client_info=client_info, + ), + self.get_intent: gapic_v1.method.wrap_method( + self.get_intent, + default_timeout=None, + client_info=client_info, + ), + self.create_intent: gapic_v1.method.wrap_method( + self.create_intent, + default_timeout=None, + client_info=client_info, + ), + self.update_intent: gapic_v1.method.wrap_method( + self.update_intent, + default_timeout=None, + client_info=client_info, + ), + self.delete_intent: gapic_v1.method.wrap_method( + self.delete_intent, + default_timeout=None, + client_info=client_info, + ), + self.batch_update_intents: gapic_v1.method.wrap_method( + self.batch_update_intents, + default_timeout=None, + client_info=client_info, + ), + self.batch_delete_intents: gapic_v1.method.wrap_method( + self.batch_delete_intents, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_intents(self) -> Callable[ + [intent.ListIntentsRequest], + Union[ + intent.ListIntentsResponse, + Awaitable[intent.ListIntentsResponse] + ]]: + raise NotImplementedError() + + @property + def get_intent(self) -> Callable[ + [intent.GetIntentRequest], + Union[ + intent.Intent, + Awaitable[intent.Intent] + ]]: + raise NotImplementedError() + + @property + def create_intent(self) -> Callable[ + [gcd_intent.CreateIntentRequest], + Union[ + gcd_intent.Intent, + Awaitable[gcd_intent.Intent] + ]]: + raise NotImplementedError() + + @property + def update_intent(self) -> Callable[ + [gcd_intent.UpdateIntentRequest], + Union[ + gcd_intent.Intent, + Awaitable[gcd_intent.Intent] + ]]: + raise NotImplementedError() + + @property + def delete_intent(self) -> Callable[ + [intent.DeleteIntentRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def batch_update_intents(self) -> Callable[ + [intent.BatchUpdateIntentsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def batch_delete_intents(self) -> Callable[ + [intent.BatchDeleteIntentsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'IntentsTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc.py new file mode 100644 index 000000000..a08adadfa --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc.py @@ -0,0 +1,474 @@ +# -*- 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 +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import intent +from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import IntentsTransport, DEFAULT_CLIENT_INFO + + +class IntentsGrpcTransport(IntentsTransport): + """gRPC backend transport for Intents. + + Service for managing + [Intents][google.cloud.dialogflow.v2beta1.Intent]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 = 'dialogflow.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 list_intents(self) -> Callable[ + [intent.ListIntentsRequest], + intent.ListIntentsResponse]: + r"""Return a callable for the list intents method over gRPC. + + Returns the list of all intents in the specified + agent. + + Returns: + Callable[[~.ListIntentsRequest], + ~.ListIntentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_intents' not in self._stubs: + self._stubs['list_intents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Intents/ListIntents', + request_serializer=intent.ListIntentsRequest.serialize, + response_deserializer=intent.ListIntentsResponse.deserialize, + ) + return self._stubs['list_intents'] + + @property + def get_intent(self) -> Callable[ + [intent.GetIntentRequest], + intent.Intent]: + r"""Return a callable for the get intent method over gRPC. + + Retrieves the specified intent. + + Returns: + Callable[[~.GetIntentRequest], + ~.Intent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_intent' not in self._stubs: + self._stubs['get_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Intents/GetIntent', + request_serializer=intent.GetIntentRequest.serialize, + response_deserializer=intent.Intent.deserialize, + ) + return self._stubs['get_intent'] + + @property + def create_intent(self) -> Callable[ + [gcd_intent.CreateIntentRequest], + gcd_intent.Intent]: + r"""Return a callable for the create intent method over gRPC. + + Creates an intent in the specified agent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.CreateIntentRequest], + ~.Intent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_intent' not in self._stubs: + self._stubs['create_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Intents/CreateIntent', + request_serializer=gcd_intent.CreateIntentRequest.serialize, + response_deserializer=gcd_intent.Intent.deserialize, + ) + return self._stubs['create_intent'] + + @property + def update_intent(self) -> Callable[ + [gcd_intent.UpdateIntentRequest], + gcd_intent.Intent]: + r"""Return a callable for the update intent method over gRPC. + + Updates the specified intent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.UpdateIntentRequest], + ~.Intent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_intent' not in self._stubs: + self._stubs['update_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Intents/UpdateIntent', + request_serializer=gcd_intent.UpdateIntentRequest.serialize, + response_deserializer=gcd_intent.Intent.deserialize, + ) + return self._stubs['update_intent'] + + @property + def delete_intent(self) -> Callable[ + [intent.DeleteIntentRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete intent method over gRPC. + + Deletes the specified intent and its direct or indirect followup + intents. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.DeleteIntentRequest], + ~.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_intent' not in self._stubs: + self._stubs['delete_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Intents/DeleteIntent', + request_serializer=intent.DeleteIntentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_intent'] + + @property + def batch_update_intents(self) -> Callable[ + [intent.BatchUpdateIntentsRequest], + operations_pb2.Operation]: + r"""Return a callable for the batch update intents method over gRPC. + + Updates/Creates multiple intents in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [BatchUpdateIntentsResponse][google.cloud.dialogflow.v2beta1.BatchUpdateIntentsResponse] + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.BatchUpdateIntentsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_update_intents' not in self._stubs: + self._stubs['batch_update_intents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Intents/BatchUpdateIntents', + request_serializer=intent.BatchUpdateIntentsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_update_intents'] + + @property + def batch_delete_intents(self) -> Callable[ + [intent.BatchDeleteIntentsRequest], + operations_pb2.Operation]: + r"""Return a callable for the batch delete intents method over gRPC. + + Deletes intents in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.BatchDeleteIntentsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_delete_intents' not in self._stubs: + self._stubs['batch_delete_intents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Intents/BatchDeleteIntents', + request_serializer=intent.BatchDeleteIntentsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_delete_intents'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'IntentsGrpcTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc_asyncio.py new file mode 100644 index 000000000..ea09e02fb --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc_asyncio.py @@ -0,0 +1,478 @@ +# -*- 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 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import intent +from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import IntentsTransport, DEFAULT_CLIENT_INFO +from .grpc import IntentsGrpcTransport + + +class IntentsGrpcAsyncIOTransport(IntentsTransport): + """gRPC AsyncIO backend transport for Intents. + + Service for managing + [Intents][google.cloud.dialogflow.v2beta1.Intent]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + 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 list_intents(self) -> Callable[ + [intent.ListIntentsRequest], + Awaitable[intent.ListIntentsResponse]]: + r"""Return a callable for the list intents method over gRPC. + + Returns the list of all intents in the specified + agent. + + Returns: + Callable[[~.ListIntentsRequest], + Awaitable[~.ListIntentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_intents' not in self._stubs: + self._stubs['list_intents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Intents/ListIntents', + request_serializer=intent.ListIntentsRequest.serialize, + response_deserializer=intent.ListIntentsResponse.deserialize, + ) + return self._stubs['list_intents'] + + @property + def get_intent(self) -> Callable[ + [intent.GetIntentRequest], + Awaitable[intent.Intent]]: + r"""Return a callable for the get intent method over gRPC. + + Retrieves the specified intent. + + Returns: + Callable[[~.GetIntentRequest], + Awaitable[~.Intent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_intent' not in self._stubs: + self._stubs['get_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Intents/GetIntent', + request_serializer=intent.GetIntentRequest.serialize, + response_deserializer=intent.Intent.deserialize, + ) + return self._stubs['get_intent'] + + @property + def create_intent(self) -> Callable[ + [gcd_intent.CreateIntentRequest], + Awaitable[gcd_intent.Intent]]: + r"""Return a callable for the create intent method over gRPC. + + Creates an intent in the specified agent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.CreateIntentRequest], + Awaitable[~.Intent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_intent' not in self._stubs: + self._stubs['create_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Intents/CreateIntent', + request_serializer=gcd_intent.CreateIntentRequest.serialize, + response_deserializer=gcd_intent.Intent.deserialize, + ) + return self._stubs['create_intent'] + + @property + def update_intent(self) -> Callable[ + [gcd_intent.UpdateIntentRequest], + Awaitable[gcd_intent.Intent]]: + r"""Return a callable for the update intent method over gRPC. + + Updates the specified intent. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.UpdateIntentRequest], + Awaitable[~.Intent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_intent' not in self._stubs: + self._stubs['update_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Intents/UpdateIntent', + request_serializer=gcd_intent.UpdateIntentRequest.serialize, + response_deserializer=gcd_intent.Intent.deserialize, + ) + return self._stubs['update_intent'] + + @property + def delete_intent(self) -> Callable[ + [intent.DeleteIntentRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete intent method over gRPC. + + Deletes the specified intent and its direct or indirect followup + intents. + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.DeleteIntentRequest], + 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_intent' not in self._stubs: + self._stubs['delete_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Intents/DeleteIntent', + request_serializer=intent.DeleteIntentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_intent'] + + @property + def batch_update_intents(self) -> Callable[ + [intent.BatchUpdateIntentsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the batch update intents method over gRPC. + + Updates/Creates multiple intents in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [BatchUpdateIntentsResponse][google.cloud.dialogflow.v2beta1.BatchUpdateIntentsResponse] + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.BatchUpdateIntentsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_update_intents' not in self._stubs: + self._stubs['batch_update_intents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Intents/BatchUpdateIntents', + request_serializer=intent.BatchUpdateIntentsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_update_intents'] + + @property + def batch_delete_intents(self) -> Callable[ + [intent.BatchDeleteIntentsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the batch delete intents method over gRPC. + + Deletes intents in the specified agent. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train an agent prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.BatchDeleteIntentsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_delete_intents' not in self._stubs: + self._stubs['batch_delete_intents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Intents/BatchDeleteIntents', + request_serializer=intent.BatchDeleteIntentsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_delete_intents'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'IntentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/__init__.py new file mode 100644 index 000000000..670d8e66d --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/__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 KnowledgeBasesClient +from .async_client import KnowledgeBasesAsyncClient + +__all__ = ( + 'KnowledgeBasesClient', + 'KnowledgeBasesAsyncClient', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/async_client.py new file mode 100644 index 000000000..5a7e51024 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/async_client.py @@ -0,0 +1,622 @@ +# -*- 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 + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2beta1.services.knowledge_bases import pagers +from google.cloud.dialogflow_v2beta1.types import knowledge_base +from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import KnowledgeBasesGrpcAsyncIOTransport +from .client import KnowledgeBasesClient + + +class KnowledgeBasesAsyncClient: + """Service for managing + [KnowledgeBases][google.cloud.dialogflow.v2beta1.KnowledgeBase]. + """ + + _client: KnowledgeBasesClient + + DEFAULT_ENDPOINT = KnowledgeBasesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = KnowledgeBasesClient.DEFAULT_MTLS_ENDPOINT + + knowledge_base_path = staticmethod(KnowledgeBasesClient.knowledge_base_path) + parse_knowledge_base_path = staticmethod(KnowledgeBasesClient.parse_knowledge_base_path) + common_billing_account_path = staticmethod(KnowledgeBasesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(KnowledgeBasesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(KnowledgeBasesClient.common_folder_path) + parse_common_folder_path = staticmethod(KnowledgeBasesClient.parse_common_folder_path) + common_organization_path = staticmethod(KnowledgeBasesClient.common_organization_path) + parse_common_organization_path = staticmethod(KnowledgeBasesClient.parse_common_organization_path) + common_project_path = staticmethod(KnowledgeBasesClient.common_project_path) + parse_common_project_path = staticmethod(KnowledgeBasesClient.parse_common_project_path) + common_location_path = staticmethod(KnowledgeBasesClient.common_location_path) + parse_common_location_path = staticmethod(KnowledgeBasesClient.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: + KnowledgeBasesAsyncClient: The constructed client. + """ + return KnowledgeBasesClient.from_service_account_info.__func__(KnowledgeBasesAsyncClient, 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: + KnowledgeBasesAsyncClient: The constructed client. + """ + return KnowledgeBasesClient.from_service_account_file.__func__(KnowledgeBasesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> KnowledgeBasesTransport: + """Returns the transport used by the client instance. + + Returns: + KnowledgeBasesTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(KnowledgeBasesClient).get_transport_class, type(KnowledgeBasesClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, KnowledgeBasesTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the knowledge bases 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, ~.KnowledgeBasesTransport]): 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 = KnowledgeBasesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_knowledge_bases(self, + request: Union[knowledge_base.ListKnowledgeBasesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListKnowledgeBasesAsyncPager: + r"""Returns the list of all knowledge bases of the specified agent. + + Note: The ``projects.agent.knowledgeBases`` resource is + deprecated; only use ``projects.knowledgeBases``. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListKnowledgeBasesRequest, dict]): + The request object. Request message for + [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2beta1.KnowledgeBases.ListKnowledgeBases]. + parent (:class:`str`): + Required. The project to list of knowledge bases for. + Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.services.knowledge_bases.pagers.ListKnowledgeBasesAsyncPager: + Response message for + [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2beta1.KnowledgeBases.ListKnowledgeBases]. + + 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 = knowledge_base.ListKnowledgeBasesRequest(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_knowledge_bases, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListKnowledgeBasesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_knowledge_base(self, + request: Union[knowledge_base.GetKnowledgeBaseRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> knowledge_base.KnowledgeBase: + r"""Retrieves the specified knowledge base. + + Note: The ``projects.agent.knowledgeBases`` resource is + deprecated; only use ``projects.knowledgeBases``. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetKnowledgeBaseRequest, dict]): + The request object. Request message for + [KnowledgeBases.GetKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.GetKnowledgeBase]. + name (:class:`str`): + Required. The name of the knowledge base to retrieve. + Format + ``projects//locations//knowledgeBases/``. + + 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.dialogflow_v2beta1.types.KnowledgeBase: + A knowledge base represents a collection of knowledge documents that you + provide to Dialogflow. Your knowledge documents + contain information that may be useful during + conversations with end-users. Some Dialogflow + features use knowledge bases when looking for a + response to an end-user input. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases resource is + deprecated; only use projects.knowledgeBases. + + """ + # 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 = knowledge_base.GetKnowledgeBaseRequest(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_knowledge_base, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_knowledge_base(self, + request: Union[gcd_knowledge_base.CreateKnowledgeBaseRequest, dict] = None, + *, + parent: str = None, + knowledge_base: gcd_knowledge_base.KnowledgeBase = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_knowledge_base.KnowledgeBase: + r"""Creates a knowledge base. + + Note: The ``projects.agent.knowledgeBases`` resource is + deprecated; only use ``projects.knowledgeBases``. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.CreateKnowledgeBaseRequest, dict]): + The request object. Request message for + [KnowledgeBases.CreateKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.CreateKnowledgeBase]. + parent (:class:`str`): + Required. The project to create a knowledge base for. + Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + knowledge_base (:class:`google.cloud.dialogflow_v2beta1.types.KnowledgeBase`): + Required. The knowledge base to + create. + + This corresponds to the ``knowledge_base`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.KnowledgeBase: + A knowledge base represents a collection of knowledge documents that you + provide to Dialogflow. Your knowledge documents + contain information that may be useful during + conversations with end-users. Some Dialogflow + features use knowledge bases when looking for a + response to an end-user input. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases resource is + deprecated; only use projects.knowledgeBases. + + """ + # 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, knowledge_base]) + if request is 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 = gcd_knowledge_base.CreateKnowledgeBaseRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if knowledge_base is not None: + request.knowledge_base = knowledge_base + + # 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_knowledge_base, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_knowledge_base(self, + request: Union[knowledge_base.DeleteKnowledgeBaseRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified knowledge base. + + Note: The ``projects.agent.knowledgeBases`` resource is + deprecated; only use ``projects.knowledgeBases``. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.DeleteKnowledgeBaseRequest, dict]): + The request object. Request message for + [KnowledgeBases.DeleteKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.DeleteKnowledgeBase]. + name (:class:`str`): + Required. The name of the knowledge base to delete. + Format: + ``projects//locations//knowledgeBases/``. + + 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 = knowledge_base.DeleteKnowledgeBaseRequest(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_knowledge_base, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def update_knowledge_base(self, + request: Union[gcd_knowledge_base.UpdateKnowledgeBaseRequest, dict] = None, + *, + knowledge_base: gcd_knowledge_base.KnowledgeBase = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_knowledge_base.KnowledgeBase: + r"""Updates the specified knowledge base. + + Note: The ``projects.agent.knowledgeBases`` resource is + deprecated; only use ``projects.knowledgeBases``. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.UpdateKnowledgeBaseRequest, dict]): + The request object. Request message for + [KnowledgeBases.UpdateKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.UpdateKnowledgeBase]. + knowledge_base (:class:`google.cloud.dialogflow_v2beta1.types.KnowledgeBase`): + Required. The knowledge base to + update. + + This corresponds to the ``knowledge_base`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Not specified means ``update all``. Currently, + only ``display_name`` can be updated, an InvalidArgument + will be returned for attempting to update other 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.dialogflow_v2beta1.types.KnowledgeBase: + A knowledge base represents a collection of knowledge documents that you + provide to Dialogflow. Your knowledge documents + contain information that may be useful during + conversations with end-users. Some Dialogflow + features use knowledge bases when looking for a + response to an end-user input. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases resource is + deprecated; only use projects.knowledgeBases. + + """ + # 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([knowledge_base, 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 = gcd_knowledge_base.UpdateKnowledgeBaseRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if knowledge_base is not None: + request.knowledge_base = knowledge_base + 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_knowledge_base, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("knowledge_base.name", request.knowledge_base.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "KnowledgeBasesAsyncClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/client.py new file mode 100644 index 000000000..a12983393 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/client.py @@ -0,0 +1,820 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2beta1.services.knowledge_bases import pagers +from google.cloud.dialogflow_v2beta1.types import knowledge_base +from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import KnowledgeBasesGrpcTransport +from .transports.grpc_asyncio import KnowledgeBasesGrpcAsyncIOTransport + + +class KnowledgeBasesClientMeta(type): + """Metaclass for the KnowledgeBases 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[KnowledgeBasesTransport]] + _transport_registry["grpc"] = KnowledgeBasesGrpcTransport + _transport_registry["grpc_asyncio"] = KnowledgeBasesGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[KnowledgeBasesTransport]: + """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 KnowledgeBasesClient(metaclass=KnowledgeBasesClientMeta): + """Service for managing + [KnowledgeBases][google.cloud.dialogflow.v2beta1.KnowledgeBase]. + """ + + @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 = "dialogflow.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: + KnowledgeBasesClient: 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: + KnowledgeBasesClient: 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) -> KnowledgeBasesTransport: + """Returns the transport used by the client instance. + + Returns: + KnowledgeBasesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def knowledge_base_path(project: str,knowledge_base: str,) -> str: + """Returns a fully-qualified knowledge_base string.""" + return "projects/{project}/knowledgeBases/{knowledge_base}".format(project=project, knowledge_base=knowledge_base, ) + + @staticmethod + def parse_knowledge_base_path(path: str) -> Dict[str,str]: + """Parses a knowledge_base path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/knowledgeBases/(?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, KnowledgeBasesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the knowledge bases 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, KnowledgeBasesTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, KnowledgeBasesTransport): + # transport is a KnowledgeBasesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_knowledge_bases(self, + request: Union[knowledge_base.ListKnowledgeBasesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListKnowledgeBasesPager: + r"""Returns the list of all knowledge bases of the specified agent. + + Note: The ``projects.agent.knowledgeBases`` resource is + deprecated; only use ``projects.knowledgeBases``. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListKnowledgeBasesRequest, dict]): + The request object. Request message for + [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2beta1.KnowledgeBases.ListKnowledgeBases]. + parent (str): + Required. The project to list of knowledge bases for. + Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.services.knowledge_bases.pagers.ListKnowledgeBasesPager: + Response message for + [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2beta1.KnowledgeBases.ListKnowledgeBases]. + + 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 knowledge_base.ListKnowledgeBasesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, knowledge_base.ListKnowledgeBasesRequest): + request = knowledge_base.ListKnowledgeBasesRequest(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_knowledge_bases] + + # Certain 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.ListKnowledgeBasesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_knowledge_base(self, + request: Union[knowledge_base.GetKnowledgeBaseRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> knowledge_base.KnowledgeBase: + r"""Retrieves the specified knowledge base. + + Note: The ``projects.agent.knowledgeBases`` resource is + deprecated; only use ``projects.knowledgeBases``. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetKnowledgeBaseRequest, dict]): + The request object. Request message for + [KnowledgeBases.GetKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.GetKnowledgeBase]. + name (str): + Required. The name of the knowledge base to retrieve. + Format + ``projects//locations//knowledgeBases/``. + + 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.dialogflow_v2beta1.types.KnowledgeBase: + A knowledge base represents a collection of knowledge documents that you + provide to Dialogflow. Your knowledge documents + contain information that may be useful during + conversations with end-users. Some Dialogflow + features use knowledge bases when looking for a + response to an end-user input. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases resource is + deprecated; only use projects.knowledgeBases. + + """ + # 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 knowledge_base.GetKnowledgeBaseRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, knowledge_base.GetKnowledgeBaseRequest): + request = knowledge_base.GetKnowledgeBaseRequest(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_knowledge_base] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_knowledge_base(self, + request: Union[gcd_knowledge_base.CreateKnowledgeBaseRequest, dict] = None, + *, + parent: str = None, + knowledge_base: gcd_knowledge_base.KnowledgeBase = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_knowledge_base.KnowledgeBase: + r"""Creates a knowledge base. + + Note: The ``projects.agent.knowledgeBases`` resource is + deprecated; only use ``projects.knowledgeBases``. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.CreateKnowledgeBaseRequest, dict]): + The request object. Request message for + [KnowledgeBases.CreateKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.CreateKnowledgeBase]. + parent (str): + Required. The project to create a knowledge base for. + Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + knowledge_base (google.cloud.dialogflow_v2beta1.types.KnowledgeBase): + Required. The knowledge base to + create. + + This corresponds to the ``knowledge_base`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.KnowledgeBase: + A knowledge base represents a collection of knowledge documents that you + provide to Dialogflow. Your knowledge documents + contain information that may be useful during + conversations with end-users. Some Dialogflow + features use knowledge bases when looking for a + response to an end-user input. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases resource is + deprecated; only use projects.knowledgeBases. + + """ + # 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, knowledge_base]) + if request is 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 gcd_knowledge_base.CreateKnowledgeBaseRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_knowledge_base.CreateKnowledgeBaseRequest): + request = gcd_knowledge_base.CreateKnowledgeBaseRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if knowledge_base is not None: + request.knowledge_base = knowledge_base + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_knowledge_base] + + # Certain 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 delete_knowledge_base(self, + request: Union[knowledge_base.DeleteKnowledgeBaseRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified knowledge base. + + Note: The ``projects.agent.knowledgeBases`` resource is + deprecated; only use ``projects.knowledgeBases``. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.DeleteKnowledgeBaseRequest, dict]): + The request object. Request message for + [KnowledgeBases.DeleteKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.DeleteKnowledgeBase]. + name (str): + Required. The name of the knowledge base to delete. + Format: + ``projects//locations//knowledgeBases/``. + + 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 knowledge_base.DeleteKnowledgeBaseRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, knowledge_base.DeleteKnowledgeBaseRequest): + request = knowledge_base.DeleteKnowledgeBaseRequest(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_knowledge_base] + + # Certain 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 update_knowledge_base(self, + request: Union[gcd_knowledge_base.UpdateKnowledgeBaseRequest, dict] = None, + *, + knowledge_base: gcd_knowledge_base.KnowledgeBase = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_knowledge_base.KnowledgeBase: + r"""Updates the specified knowledge base. + + Note: The ``projects.agent.knowledgeBases`` resource is + deprecated; only use ``projects.knowledgeBases``. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.UpdateKnowledgeBaseRequest, dict]): + The request object. Request message for + [KnowledgeBases.UpdateKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.UpdateKnowledgeBase]. + knowledge_base (google.cloud.dialogflow_v2beta1.types.KnowledgeBase): + Required. The knowledge base to + update. + + This corresponds to the ``knowledge_base`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Not specified means ``update all``. Currently, + only ``display_name`` can be updated, an InvalidArgument + will be returned for attempting to update other 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.dialogflow_v2beta1.types.KnowledgeBase: + A knowledge base represents a collection of knowledge documents that you + provide to Dialogflow. Your knowledge documents + contain information that may be useful during + conversations with end-users. Some Dialogflow + features use knowledge bases when looking for a + response to an end-user input. + + For more information, see the [knowledge base + guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). + + Note: The projects.agent.knowledgeBases resource is + deprecated; only use projects.knowledgeBases. + + """ + # 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([knowledge_base, 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 gcd_knowledge_base.UpdateKnowledgeBaseRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_knowledge_base.UpdateKnowledgeBaseRequest): + request = gcd_knowledge_base.UpdateKnowledgeBaseRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if knowledge_base is not None: + request.knowledge_base = knowledge_base + 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_knowledge_base] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("knowledge_base.name", request.knowledge_base.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "KnowledgeBasesClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/pagers.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/pagers.py new file mode 100644 index 000000000..659bb6516 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflow_v2beta1.types import knowledge_base + + +class ListKnowledgeBasesPager: + """A pager for iterating through ``list_knowledge_bases`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListKnowledgeBasesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``knowledge_bases`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListKnowledgeBases`` requests and continue to iterate + through the ``knowledge_bases`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListKnowledgeBasesResponse` + 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[..., knowledge_base.ListKnowledgeBasesResponse], + request: knowledge_base.ListKnowledgeBasesRequest, + response: knowledge_base.ListKnowledgeBasesResponse, + *, + 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.dialogflow_v2beta1.types.ListKnowledgeBasesRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListKnowledgeBasesResponse): + 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 = knowledge_base.ListKnowledgeBasesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[knowledge_base.ListKnowledgeBasesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[knowledge_base.KnowledgeBase]: + for page in self.pages: + yield from page.knowledge_bases + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListKnowledgeBasesAsyncPager: + """A pager for iterating through ``list_knowledge_bases`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListKnowledgeBasesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``knowledge_bases`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListKnowledgeBases`` requests and continue to iterate + through the ``knowledge_bases`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListKnowledgeBasesResponse` + 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[knowledge_base.ListKnowledgeBasesResponse]], + request: knowledge_base.ListKnowledgeBasesRequest, + response: knowledge_base.ListKnowledgeBasesResponse, + *, + 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.dialogflow_v2beta1.types.ListKnowledgeBasesRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListKnowledgeBasesResponse): + 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 = knowledge_base.ListKnowledgeBasesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[knowledge_base.ListKnowledgeBasesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[knowledge_base.KnowledgeBase]: + async def async_generator(): + async for page in self.pages: + for response in page.knowledge_bases: + 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/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/__init__.py new file mode 100644 index 000000000..c04ef7c9f --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/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 KnowledgeBasesTransport +from .grpc import KnowledgeBasesGrpcTransport +from .grpc_asyncio import KnowledgeBasesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[KnowledgeBasesTransport]] +_transport_registry['grpc'] = KnowledgeBasesGrpcTransport +_transport_registry['grpc_asyncio'] = KnowledgeBasesGrpcAsyncIOTransport + +__all__ = ( + 'KnowledgeBasesTransport', + 'KnowledgeBasesGrpcTransport', + 'KnowledgeBasesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/base.py new file mode 100644 index 000000000..3a5c5e4e6 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/base.py @@ -0,0 +1,205 @@ +# -*- 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.types import knowledge_base +from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base +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-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class KnowledgeBasesTransport(abc.ABC): + """Abstract transport class for KnowledgeBases.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_knowledge_bases: gapic_v1.method.wrap_method( + self.list_knowledge_bases, + default_timeout=None, + client_info=client_info, + ), + self.get_knowledge_base: gapic_v1.method.wrap_method( + self.get_knowledge_base, + default_timeout=None, + client_info=client_info, + ), + self.create_knowledge_base: gapic_v1.method.wrap_method( + self.create_knowledge_base, + default_timeout=None, + client_info=client_info, + ), + self.delete_knowledge_base: gapic_v1.method.wrap_method( + self.delete_knowledge_base, + default_timeout=None, + client_info=client_info, + ), + self.update_knowledge_base: gapic_v1.method.wrap_method( + self.update_knowledge_base, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_knowledge_bases(self) -> Callable[ + [knowledge_base.ListKnowledgeBasesRequest], + Union[ + knowledge_base.ListKnowledgeBasesResponse, + Awaitable[knowledge_base.ListKnowledgeBasesResponse] + ]]: + raise NotImplementedError() + + @property + def get_knowledge_base(self) -> Callable[ + [knowledge_base.GetKnowledgeBaseRequest], + Union[ + knowledge_base.KnowledgeBase, + Awaitable[knowledge_base.KnowledgeBase] + ]]: + raise NotImplementedError() + + @property + def create_knowledge_base(self) -> Callable[ + [gcd_knowledge_base.CreateKnowledgeBaseRequest], + Union[ + gcd_knowledge_base.KnowledgeBase, + Awaitable[gcd_knowledge_base.KnowledgeBase] + ]]: + raise NotImplementedError() + + @property + def delete_knowledge_base(self) -> Callable[ + [knowledge_base.DeleteKnowledgeBaseRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_knowledge_base(self) -> Callable[ + [gcd_knowledge_base.UpdateKnowledgeBaseRequest], + Union[ + gcd_knowledge_base.KnowledgeBase, + Awaitable[gcd_knowledge_base.KnowledgeBase] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'KnowledgeBasesTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc.py new file mode 100644 index 000000000..dea53bc21 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc.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. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import knowledge_base +from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base +from google.protobuf import empty_pb2 # type: ignore +from .base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO + + +class KnowledgeBasesGrpcTransport(KnowledgeBasesTransport): + """gRPC backend transport for KnowledgeBases. + + Service for managing + [KnowledgeBases][google.cloud.dialogflow.v2beta1.KnowledgeBase]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 = 'dialogflow.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 list_knowledge_bases(self) -> Callable[ + [knowledge_base.ListKnowledgeBasesRequest], + knowledge_base.ListKnowledgeBasesResponse]: + r"""Return a callable for the list knowledge bases method over gRPC. + + Returns the list of all knowledge bases of the specified agent. + + Note: The ``projects.agent.knowledgeBases`` resource is + deprecated; only use ``projects.knowledgeBases``. + + Returns: + Callable[[~.ListKnowledgeBasesRequest], + ~.ListKnowledgeBasesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_knowledge_bases' not in self._stubs: + self._stubs['list_knowledge_bases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.KnowledgeBases/ListKnowledgeBases', + request_serializer=knowledge_base.ListKnowledgeBasesRequest.serialize, + response_deserializer=knowledge_base.ListKnowledgeBasesResponse.deserialize, + ) + return self._stubs['list_knowledge_bases'] + + @property + def get_knowledge_base(self) -> Callable[ + [knowledge_base.GetKnowledgeBaseRequest], + knowledge_base.KnowledgeBase]: + r"""Return a callable for the get knowledge base method over gRPC. + + Retrieves the specified knowledge base. + + Note: The ``projects.agent.knowledgeBases`` resource is + deprecated; only use ``projects.knowledgeBases``. + + Returns: + Callable[[~.GetKnowledgeBaseRequest], + ~.KnowledgeBase]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_knowledge_base' not in self._stubs: + self._stubs['get_knowledge_base'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.KnowledgeBases/GetKnowledgeBase', + request_serializer=knowledge_base.GetKnowledgeBaseRequest.serialize, + response_deserializer=knowledge_base.KnowledgeBase.deserialize, + ) + return self._stubs['get_knowledge_base'] + + @property + def create_knowledge_base(self) -> Callable[ + [gcd_knowledge_base.CreateKnowledgeBaseRequest], + gcd_knowledge_base.KnowledgeBase]: + r"""Return a callable for the create knowledge base method over gRPC. + + Creates a knowledge base. + + Note: The ``projects.agent.knowledgeBases`` resource is + deprecated; only use ``projects.knowledgeBases``. + + Returns: + Callable[[~.CreateKnowledgeBaseRequest], + ~.KnowledgeBase]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_knowledge_base' not in self._stubs: + self._stubs['create_knowledge_base'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.KnowledgeBases/CreateKnowledgeBase', + request_serializer=gcd_knowledge_base.CreateKnowledgeBaseRequest.serialize, + response_deserializer=gcd_knowledge_base.KnowledgeBase.deserialize, + ) + return self._stubs['create_knowledge_base'] + + @property + def delete_knowledge_base(self) -> Callable[ + [knowledge_base.DeleteKnowledgeBaseRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete knowledge base method over gRPC. + + Deletes the specified knowledge base. + + Note: The ``projects.agent.knowledgeBases`` resource is + deprecated; only use ``projects.knowledgeBases``. + + Returns: + Callable[[~.DeleteKnowledgeBaseRequest], + ~.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_knowledge_base' not in self._stubs: + self._stubs['delete_knowledge_base'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.KnowledgeBases/DeleteKnowledgeBase', + request_serializer=knowledge_base.DeleteKnowledgeBaseRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_knowledge_base'] + + @property + def update_knowledge_base(self) -> Callable[ + [gcd_knowledge_base.UpdateKnowledgeBaseRequest], + gcd_knowledge_base.KnowledgeBase]: + r"""Return a callable for the update knowledge base method over gRPC. + + Updates the specified knowledge base. + + Note: The ``projects.agent.knowledgeBases`` resource is + deprecated; only use ``projects.knowledgeBases``. + + Returns: + Callable[[~.UpdateKnowledgeBaseRequest], + ~.KnowledgeBase]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_knowledge_base' not in self._stubs: + self._stubs['update_knowledge_base'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.KnowledgeBases/UpdateKnowledgeBase', + request_serializer=gcd_knowledge_base.UpdateKnowledgeBaseRequest.serialize, + response_deserializer=gcd_knowledge_base.KnowledgeBase.deserialize, + ) + return self._stubs['update_knowledge_base'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'KnowledgeBasesGrpcTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc_asyncio.py new file mode 100644 index 000000000..b26a008e5 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc_asyncio.py @@ -0,0 +1,380 @@ +# -*- 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 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import knowledge_base +from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base +from google.protobuf import empty_pb2 # type: ignore +from .base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO +from .grpc import KnowledgeBasesGrpcTransport + + +class KnowledgeBasesGrpcAsyncIOTransport(KnowledgeBasesTransport): + """gRPC AsyncIO backend transport for KnowledgeBases. + + Service for managing + [KnowledgeBases][google.cloud.dialogflow.v2beta1.KnowledgeBase]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 list_knowledge_bases(self) -> Callable[ + [knowledge_base.ListKnowledgeBasesRequest], + Awaitable[knowledge_base.ListKnowledgeBasesResponse]]: + r"""Return a callable for the list knowledge bases method over gRPC. + + Returns the list of all knowledge bases of the specified agent. + + Note: The ``projects.agent.knowledgeBases`` resource is + deprecated; only use ``projects.knowledgeBases``. + + Returns: + Callable[[~.ListKnowledgeBasesRequest], + Awaitable[~.ListKnowledgeBasesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_knowledge_bases' not in self._stubs: + self._stubs['list_knowledge_bases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.KnowledgeBases/ListKnowledgeBases', + request_serializer=knowledge_base.ListKnowledgeBasesRequest.serialize, + response_deserializer=knowledge_base.ListKnowledgeBasesResponse.deserialize, + ) + return self._stubs['list_knowledge_bases'] + + @property + def get_knowledge_base(self) -> Callable[ + [knowledge_base.GetKnowledgeBaseRequest], + Awaitable[knowledge_base.KnowledgeBase]]: + r"""Return a callable for the get knowledge base method over gRPC. + + Retrieves the specified knowledge base. + + Note: The ``projects.agent.knowledgeBases`` resource is + deprecated; only use ``projects.knowledgeBases``. + + Returns: + Callable[[~.GetKnowledgeBaseRequest], + Awaitable[~.KnowledgeBase]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_knowledge_base' not in self._stubs: + self._stubs['get_knowledge_base'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.KnowledgeBases/GetKnowledgeBase', + request_serializer=knowledge_base.GetKnowledgeBaseRequest.serialize, + response_deserializer=knowledge_base.KnowledgeBase.deserialize, + ) + return self._stubs['get_knowledge_base'] + + @property + def create_knowledge_base(self) -> Callable[ + [gcd_knowledge_base.CreateKnowledgeBaseRequest], + Awaitable[gcd_knowledge_base.KnowledgeBase]]: + r"""Return a callable for the create knowledge base method over gRPC. + + Creates a knowledge base. + + Note: The ``projects.agent.knowledgeBases`` resource is + deprecated; only use ``projects.knowledgeBases``. + + Returns: + Callable[[~.CreateKnowledgeBaseRequest], + Awaitable[~.KnowledgeBase]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_knowledge_base' not in self._stubs: + self._stubs['create_knowledge_base'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.KnowledgeBases/CreateKnowledgeBase', + request_serializer=gcd_knowledge_base.CreateKnowledgeBaseRequest.serialize, + response_deserializer=gcd_knowledge_base.KnowledgeBase.deserialize, + ) + return self._stubs['create_knowledge_base'] + + @property + def delete_knowledge_base(self) -> Callable[ + [knowledge_base.DeleteKnowledgeBaseRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete knowledge base method over gRPC. + + Deletes the specified knowledge base. + + Note: The ``projects.agent.knowledgeBases`` resource is + deprecated; only use ``projects.knowledgeBases``. + + Returns: + Callable[[~.DeleteKnowledgeBaseRequest], + 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_knowledge_base' not in self._stubs: + self._stubs['delete_knowledge_base'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.KnowledgeBases/DeleteKnowledgeBase', + request_serializer=knowledge_base.DeleteKnowledgeBaseRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_knowledge_base'] + + @property + def update_knowledge_base(self) -> Callable[ + [gcd_knowledge_base.UpdateKnowledgeBaseRequest], + Awaitable[gcd_knowledge_base.KnowledgeBase]]: + r"""Return a callable for the update knowledge base method over gRPC. + + Updates the specified knowledge base. + + Note: The ``projects.agent.knowledgeBases`` resource is + deprecated; only use ``projects.knowledgeBases``. + + Returns: + Callable[[~.UpdateKnowledgeBaseRequest], + Awaitable[~.KnowledgeBase]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_knowledge_base' not in self._stubs: + self._stubs['update_knowledge_base'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.KnowledgeBases/UpdateKnowledgeBase', + request_serializer=gcd_knowledge_base.UpdateKnowledgeBaseRequest.serialize, + response_deserializer=gcd_knowledge_base.KnowledgeBase.deserialize, + ) + return self._stubs['update_knowledge_base'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'KnowledgeBasesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/__init__.py new file mode 100644 index 000000000..376e9e7d4 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/__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 ParticipantsClient +from .async_client import ParticipantsAsyncClient + +__all__ = ( + 'ParticipantsClient', + 'ParticipantsAsyncClient', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/async_client.py new file mode 100644 index 000000000..ed0bc5299 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/async_client.py @@ -0,0 +1,1021 @@ +# -*- 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 warnings + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2beta1.services.participants import pagers +from google.cloud.dialogflow_v2beta1.types import participant +from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant +from google.cloud.dialogflow_v2beta1.types import session +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ParticipantsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ParticipantsGrpcAsyncIOTransport +from .client import ParticipantsClient + + +class ParticipantsAsyncClient: + """Service for managing + [Participants][google.cloud.dialogflow.v2beta1.Participant]. + """ + + _client: ParticipantsClient + + DEFAULT_ENDPOINT = ParticipantsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ParticipantsClient.DEFAULT_MTLS_ENDPOINT + + context_path = staticmethod(ParticipantsClient.context_path) + parse_context_path = staticmethod(ParticipantsClient.parse_context_path) + document_path = staticmethod(ParticipantsClient.document_path) + parse_document_path = staticmethod(ParticipantsClient.parse_document_path) + intent_path = staticmethod(ParticipantsClient.intent_path) + parse_intent_path = staticmethod(ParticipantsClient.parse_intent_path) + message_path = staticmethod(ParticipantsClient.message_path) + parse_message_path = staticmethod(ParticipantsClient.parse_message_path) + participant_path = staticmethod(ParticipantsClient.participant_path) + parse_participant_path = staticmethod(ParticipantsClient.parse_participant_path) + session_entity_type_path = staticmethod(ParticipantsClient.session_entity_type_path) + parse_session_entity_type_path = staticmethod(ParticipantsClient.parse_session_entity_type_path) + common_billing_account_path = staticmethod(ParticipantsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ParticipantsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ParticipantsClient.common_folder_path) + parse_common_folder_path = staticmethod(ParticipantsClient.parse_common_folder_path) + common_organization_path = staticmethod(ParticipantsClient.common_organization_path) + parse_common_organization_path = staticmethod(ParticipantsClient.parse_common_organization_path) + common_project_path = staticmethod(ParticipantsClient.common_project_path) + parse_common_project_path = staticmethod(ParticipantsClient.parse_common_project_path) + common_location_path = staticmethod(ParticipantsClient.common_location_path) + parse_common_location_path = staticmethod(ParticipantsClient.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: + ParticipantsAsyncClient: The constructed client. + """ + return ParticipantsClient.from_service_account_info.__func__(ParticipantsAsyncClient, 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: + ParticipantsAsyncClient: The constructed client. + """ + return ParticipantsClient.from_service_account_file.__func__(ParticipantsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ParticipantsTransport: + """Returns the transport used by the client instance. + + Returns: + ParticipantsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ParticipantsClient).get_transport_class, type(ParticipantsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ParticipantsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the participants 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, ~.ParticipantsTransport]): 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 = ParticipantsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_participant(self, + request: Union[gcd_participant.CreateParticipantRequest, dict] = None, + *, + parent: str = None, + participant: gcd_participant.Participant = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_participant.Participant: + r"""Creates a new participant in a conversation. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.CreateParticipantRequest, dict]): + The request object. The request message for + [Participants.CreateParticipant][google.cloud.dialogflow.v2beta1.Participants.CreateParticipant]. + parent (:class:`str`): + Required. Resource identifier of the conversation adding + the participant. Format: + ``projects//locations//conversations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + participant (:class:`google.cloud.dialogflow_v2beta1.types.Participant`): + Required. The participant to create. + This corresponds to the ``participant`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Participant: + Represents a conversation participant + (human agent, virtual agent, end-user). + + """ + # 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, participant]) + if request is 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 = gcd_participant.CreateParticipantRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if participant is not None: + request.participant = participant + + # 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_participant, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_participant(self, + request: Union[participant.GetParticipantRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.Participant: + r"""Retrieves a conversation participant. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetParticipantRequest, dict]): + The request object. The request message for + [Participants.GetParticipant][google.cloud.dialogflow.v2beta1.Participants.GetParticipant]. + name (:class:`str`): + Required. The name of the participant. Format: + ``projects//locations//conversations//participants/``. + + 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.dialogflow_v2beta1.types.Participant: + Represents a conversation participant + (human agent, virtual agent, end-user). + + """ + # 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 = participant.GetParticipantRequest(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_participant, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_participants(self, + request: Union[participant.ListParticipantsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListParticipantsAsyncPager: + r"""Returns the list of all participants in the specified + conversation. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListParticipantsRequest, dict]): + The request object. The request message for + [Participants.ListParticipants][google.cloud.dialogflow.v2beta1.Participants.ListParticipants]. + parent (:class:`str`): + Required. The conversation to list all participants + from. Format: + ``projects//locations//conversations/``. + + 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.dialogflow_v2beta1.services.participants.pagers.ListParticipantsAsyncPager: + The response message for + [Participants.ListParticipants][google.cloud.dialogflow.v2beta1.Participants.ListParticipants]. + + 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 = participant.ListParticipantsRequest(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_participants, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListParticipantsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_participant(self, + request: Union[gcd_participant.UpdateParticipantRequest, dict] = None, + *, + participant: gcd_participant.Participant = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_participant.Participant: + r"""Updates the specified participant. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.UpdateParticipantRequest, dict]): + The request object. The request message for + [Participants.UpdateParticipant][google.cloud.dialogflow.v2beta1.Participants.UpdateParticipant]. + participant (:class:`google.cloud.dialogflow_v2beta1.types.Participant`): + Required. The participant to update. + This corresponds to the ``participant`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The mask to specify which + fields to update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Participant: + Represents a conversation participant + (human agent, virtual agent, end-user). + + """ + # 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([participant, 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 = gcd_participant.UpdateParticipantRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if participant is not None: + request.participant = participant + 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_participant, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("participant.name", request.participant.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def analyze_content(self, + request: Union[gcd_participant.AnalyzeContentRequest, dict] = None, + *, + participant: str = None, + text_input: session.TextInput = None, + event_input: session.EventInput = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_participant.AnalyzeContentResponse: + r"""Adds a text (chat, for example), or audio (phone recording, for + example) message from a participant into the conversation. + + Note: Always use agent versions for production traffic sent to + virtual agents. See `Versions and + environments `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.AnalyzeContentRequest, dict]): + The request object. The request message for + [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent]. + participant (:class:`str`): + Required. The name of the participant this text comes + from. Format: + ``projects//locations//conversations//participants/``. + + This corresponds to the ``participant`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + text_input (:class:`google.cloud.dialogflow_v2beta1.types.TextInput`): + The natural language text to be + processed. + + This corresponds to the ``text_input`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + event_input (:class:`google.cloud.dialogflow_v2beta1.types.EventInput`): + An input event to send to Dialogflow. + This corresponds to the ``event_input`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.AnalyzeContentResponse: + The response message for + [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent]. + + """ + # 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([participant, text_input, event_input]) + if request is 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 = gcd_participant.AnalyzeContentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if participant is not None: + request.participant = participant + if text_input is not None: + request.text_input = text_input + if event_input is not None: + request.event_input = event_input + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.analyze_content, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=220.0, + ), + default_timeout=220.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(( + ("participant", request.participant), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def suggest_articles(self, + request: Union[participant.SuggestArticlesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.SuggestArticlesResponse: + r"""Gets suggested articles for a participant based on specific + historical messages. + + Note that + [ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions] + will only list the auto-generated suggestions, while + [CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion] + will try to compile suggestion based on the provided + conversation context in the real time. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.SuggestArticlesRequest, dict]): + The request object. The request message for + [Participants.SuggestArticles][google.cloud.dialogflow.v2beta1.Participants.SuggestArticles]. + parent (:class:`str`): + Required. The name of the participant to fetch + suggestion for. Format: + ``projects//locations//conversations//participants/``. + + 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.dialogflow_v2beta1.types.SuggestArticlesResponse: + The response message for + [Participants.SuggestArticles][google.cloud.dialogflow.v2beta1.Participants.SuggestArticles]. + + """ + # 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 = participant.SuggestArticlesRequest(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.suggest_articles, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def suggest_faq_answers(self, + request: Union[participant.SuggestFaqAnswersRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.SuggestFaqAnswersResponse: + r"""Gets suggested faq answers for a participant based on + specific historical messages. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.SuggestFaqAnswersRequest, dict]): + The request object. The request message for + [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers]. + parent (:class:`str`): + Required. The name of the participant to fetch + suggestion for. Format: + ``projects//locations//conversations//participants/``. + + 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.dialogflow_v2beta1.types.SuggestFaqAnswersResponse: + The request message for + [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers]. + + """ + # 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 = participant.SuggestFaqAnswersRequest(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.suggest_faq_answers, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def suggest_smart_replies(self, + request: Union[participant.SuggestSmartRepliesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.SuggestSmartRepliesResponse: + r"""Gets smart replies for a participant based on + specific historical messages. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.SuggestSmartRepliesRequest, dict]): + The request object. The request message for + [Participants.SuggestSmartReplies][google.cloud.dialogflow.v2beta1.Participants.SuggestSmartReplies]. + parent (:class:`str`): + Required. The name of the participant to fetch + suggestion for. Format: + ``projects//locations//conversations//participants/``. + + 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.dialogflow_v2beta1.types.SuggestSmartRepliesResponse: + The response message for + [Participants.SuggestSmartReplies][google.cloud.dialogflow.v2beta1.Participants.SuggestSmartReplies]. + + """ + # 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 = participant.SuggestSmartRepliesRequest(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.suggest_smart_replies, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_suggestions(self, + request: Union[participant.ListSuggestionsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSuggestionsAsyncPager: + r"""Deprecated: Use inline suggestion, event based suggestion or + Suggestion\* API instead. See + [HumanAgentAssistantConfig.name][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.name] + for more details. Removal Date: 2020-09-01. + + Retrieves suggestions for live agents. + + This method should be used by human agent client software to + fetch auto generated suggestions in real-time, while the + conversation with an end user is in progress. The functionality + is implemented in terms of the `list + pagination `__ + design pattern. The client app should use the + ``next_page_token`` field to fetch the next batch of + suggestions. ``suggestions`` are sorted by ``create_time`` in + descending order. To fetch latest suggestion, just set + ``page_size`` to 1. To fetch new suggestions without + duplication, send request with filter + ``create_time_epoch_microseconds > [first item's create_time of previous request]`` + and empty page_token. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListSuggestionsRequest, dict]): + The request object. The request message for + [Participants.ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.services.participants.pagers.ListSuggestionsAsyncPager: + The response message for + [Participants.ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + warnings.warn("ParticipantsAsyncClient.list_suggestions is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + request = participant.ListSuggestionsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_suggestions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSuggestionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def compile_suggestion(self, + request: Union[participant.CompileSuggestionRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.CompileSuggestionResponse: + r"""Deprecated. use + [SuggestArticles][google.cloud.dialogflow.v2beta1.Participants.SuggestArticles] + and + [SuggestFaqAnswers][google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers] + instead. + + Gets suggestions for a participant based on specific historical + messages. + + Note that + [ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions] + will only list the auto-generated suggestions, while + [CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion] + will try to compile suggestion based on the provided + conversation context in the real time. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.CompileSuggestionRequest, dict]): + The request object. The request message for + [Participants.CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.CompileSuggestionResponse: + The response message for + [Participants.CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion]. + + """ + warnings.warn("ParticipantsAsyncClient.compile_suggestion is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + request = participant.CompileSuggestionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.compile_suggestion, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ParticipantsAsyncClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/client.py new file mode 100644 index 000000000..fe5b8115f --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/client.py @@ -0,0 +1,1260 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2beta1.services.participants import pagers +from google.cloud.dialogflow_v2beta1.types import participant +from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant +from google.cloud.dialogflow_v2beta1.types import session +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ParticipantsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ParticipantsGrpcTransport +from .transports.grpc_asyncio import ParticipantsGrpcAsyncIOTransport + + +class ParticipantsClientMeta(type): + """Metaclass for the Participants 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[ParticipantsTransport]] + _transport_registry["grpc"] = ParticipantsGrpcTransport + _transport_registry["grpc_asyncio"] = ParticipantsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ParticipantsTransport]: + """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 ParticipantsClient(metaclass=ParticipantsClientMeta): + """Service for managing + [Participants][google.cloud.dialogflow.v2beta1.Participant]. + """ + + @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 = "dialogflow.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: + ParticipantsClient: 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: + ParticipantsClient: 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) -> ParticipantsTransport: + """Returns the transport used by the client instance. + + Returns: + ParticipantsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def context_path(project: str,session: str,context: str,) -> str: + """Returns a fully-qualified context string.""" + return "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) + + @staticmethod + def parse_context_path(path: str) -> Dict[str,str]: + """Parses a context path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/contexts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def document_path(project: str,knowledge_base: str,document: str,) -> str: + """Returns a fully-qualified document string.""" + return "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format(project=project, knowledge_base=knowledge_base, document=document, ) + + @staticmethod + def parse_document_path(path: str) -> Dict[str,str]: + """Parses a document path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/knowledgeBases/(?P.+?)/documents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def intent_path(project: str,intent: str,) -> str: + """Returns a fully-qualified intent string.""" + return "projects/{project}/agent/intents/{intent}".format(project=project, intent=intent, ) + + @staticmethod + def parse_intent_path(path: str) -> Dict[str,str]: + """Parses a intent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/intents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def message_path(project: str,conversation: str,message: str,) -> str: + """Returns a fully-qualified message string.""" + return "projects/{project}/conversations/{conversation}/messages/{message}".format(project=project, conversation=conversation, message=message, ) + + @staticmethod + def parse_message_path(path: str) -> Dict[str,str]: + """Parses a message path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/conversations/(?P.+?)/messages/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def participant_path(project: str,conversation: str,participant: str,) -> str: + """Returns a fully-qualified participant string.""" + return "projects/{project}/conversations/{conversation}/participants/{participant}".format(project=project, conversation=conversation, participant=participant, ) + + @staticmethod + def parse_participant_path(path: str) -> Dict[str,str]: + """Parses a participant path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/conversations/(?P.+?)/participants/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def session_entity_type_path(project: str,session: str,entity_type: str,) -> str: + """Returns a fully-qualified session_entity_type string.""" + return "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format(project=project, session=session, entity_type=entity_type, ) + + @staticmethod + def parse_session_entity_type_path(path: str) -> Dict[str,str]: + """Parses a session_entity_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/entityTypes/(?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, ParticipantsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the participants 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, ParticipantsTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, ParticipantsTransport): + # transport is a ParticipantsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def create_participant(self, + request: Union[gcd_participant.CreateParticipantRequest, dict] = None, + *, + parent: str = None, + participant: gcd_participant.Participant = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_participant.Participant: + r"""Creates a new participant in a conversation. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.CreateParticipantRequest, dict]): + The request object. The request message for + [Participants.CreateParticipant][google.cloud.dialogflow.v2beta1.Participants.CreateParticipant]. + parent (str): + Required. Resource identifier of the conversation adding + the participant. Format: + ``projects//locations//conversations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + participant (google.cloud.dialogflow_v2beta1.types.Participant): + Required. The participant to create. + This corresponds to the ``participant`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Participant: + Represents a conversation participant + (human agent, virtual agent, end-user). + + """ + # 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, participant]) + if request is 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 gcd_participant.CreateParticipantRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_participant.CreateParticipantRequest): + request = gcd_participant.CreateParticipantRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if participant is not None: + request.participant = participant + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_participant] + + # Certain 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_participant(self, + request: Union[participant.GetParticipantRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.Participant: + r"""Retrieves a conversation participant. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetParticipantRequest, dict]): + The request object. The request message for + [Participants.GetParticipant][google.cloud.dialogflow.v2beta1.Participants.GetParticipant]. + name (str): + Required. The name of the participant. Format: + ``projects//locations//conversations//participants/``. + + 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.dialogflow_v2beta1.types.Participant: + Represents a conversation participant + (human agent, virtual agent, end-user). + + """ + # 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 participant.GetParticipantRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, participant.GetParticipantRequest): + request = participant.GetParticipantRequest(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_participant] + + # Certain 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_participants(self, + request: Union[participant.ListParticipantsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListParticipantsPager: + r"""Returns the list of all participants in the specified + conversation. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListParticipantsRequest, dict]): + The request object. The request message for + [Participants.ListParticipants][google.cloud.dialogflow.v2beta1.Participants.ListParticipants]. + parent (str): + Required. The conversation to list all participants + from. Format: + ``projects//locations//conversations/``. + + 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.dialogflow_v2beta1.services.participants.pagers.ListParticipantsPager: + The response message for + [Participants.ListParticipants][google.cloud.dialogflow.v2beta1.Participants.ListParticipants]. + + 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 participant.ListParticipantsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, participant.ListParticipantsRequest): + request = participant.ListParticipantsRequest(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_participants] + + # Certain 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.ListParticipantsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_participant(self, + request: Union[gcd_participant.UpdateParticipantRequest, dict] = None, + *, + participant: gcd_participant.Participant = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_participant.Participant: + r"""Updates the specified participant. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.UpdateParticipantRequest, dict]): + The request object. The request message for + [Participants.UpdateParticipant][google.cloud.dialogflow.v2beta1.Participants.UpdateParticipant]. + participant (google.cloud.dialogflow_v2beta1.types.Participant): + Required. The participant to update. + This corresponds to the ``participant`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to specify which + fields to update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Participant: + Represents a conversation participant + (human agent, virtual agent, end-user). + + """ + # 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([participant, 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 gcd_participant.UpdateParticipantRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_participant.UpdateParticipantRequest): + request = gcd_participant.UpdateParticipantRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if participant is not None: + request.participant = participant + 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_participant] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("participant.name", request.participant.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def analyze_content(self, + request: Union[gcd_participant.AnalyzeContentRequest, dict] = None, + *, + participant: str = None, + text_input: session.TextInput = None, + event_input: session.EventInput = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_participant.AnalyzeContentResponse: + r"""Adds a text (chat, for example), or audio (phone recording, for + example) message from a participant into the conversation. + + Note: Always use agent versions for production traffic sent to + virtual agents. See `Versions and + environments `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.AnalyzeContentRequest, dict]): + The request object. The request message for + [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent]. + participant (str): + Required. The name of the participant this text comes + from. Format: + ``projects//locations//conversations//participants/``. + + This corresponds to the ``participant`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + text_input (google.cloud.dialogflow_v2beta1.types.TextInput): + The natural language text to be + processed. + + This corresponds to the ``text_input`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + event_input (google.cloud.dialogflow_v2beta1.types.EventInput): + An input event to send to Dialogflow. + This corresponds to the ``event_input`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.AnalyzeContentResponse: + The response message for + [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent]. + + """ + # 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([participant, text_input, event_input]) + if request is 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 gcd_participant.AnalyzeContentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_participant.AnalyzeContentRequest): + request = gcd_participant.AnalyzeContentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if participant is not None: + request.participant = participant + if text_input is not None: + request.text_input = text_input + if event_input is not None: + request.event_input = event_input + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.analyze_content] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("participant", request.participant), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def suggest_articles(self, + request: Union[participant.SuggestArticlesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.SuggestArticlesResponse: + r"""Gets suggested articles for a participant based on specific + historical messages. + + Note that + [ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions] + will only list the auto-generated suggestions, while + [CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion] + will try to compile suggestion based on the provided + conversation context in the real time. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.SuggestArticlesRequest, dict]): + The request object. The request message for + [Participants.SuggestArticles][google.cloud.dialogflow.v2beta1.Participants.SuggestArticles]. + parent (str): + Required. The name of the participant to fetch + suggestion for. Format: + ``projects//locations//conversations//participants/``. + + 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.dialogflow_v2beta1.types.SuggestArticlesResponse: + The response message for + [Participants.SuggestArticles][google.cloud.dialogflow.v2beta1.Participants.SuggestArticles]. + + """ + # 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 participant.SuggestArticlesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, participant.SuggestArticlesRequest): + request = participant.SuggestArticlesRequest(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.suggest_articles] + + # Certain 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 suggest_faq_answers(self, + request: Union[participant.SuggestFaqAnswersRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.SuggestFaqAnswersResponse: + r"""Gets suggested faq answers for a participant based on + specific historical messages. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.SuggestFaqAnswersRequest, dict]): + The request object. The request message for + [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers]. + parent (str): + Required. The name of the participant to fetch + suggestion for. Format: + ``projects//locations//conversations//participants/``. + + 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.dialogflow_v2beta1.types.SuggestFaqAnswersResponse: + The request message for + [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers]. + + """ + # 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 participant.SuggestFaqAnswersRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, participant.SuggestFaqAnswersRequest): + request = participant.SuggestFaqAnswersRequest(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.suggest_faq_answers] + + # Certain 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 suggest_smart_replies(self, + request: Union[participant.SuggestSmartRepliesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.SuggestSmartRepliesResponse: + r"""Gets smart replies for a participant based on + specific historical messages. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.SuggestSmartRepliesRequest, dict]): + The request object. The request message for + [Participants.SuggestSmartReplies][google.cloud.dialogflow.v2beta1.Participants.SuggestSmartReplies]. + parent (str): + Required. The name of the participant to fetch + suggestion for. Format: + ``projects//locations//conversations//participants/``. + + 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.dialogflow_v2beta1.types.SuggestSmartRepliesResponse: + The response message for + [Participants.SuggestSmartReplies][google.cloud.dialogflow.v2beta1.Participants.SuggestSmartReplies]. + + """ + # 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 participant.SuggestSmartRepliesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, participant.SuggestSmartRepliesRequest): + request = participant.SuggestSmartRepliesRequest(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.suggest_smart_replies] + + # Certain 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_suggestions(self, + request: Union[participant.ListSuggestionsRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSuggestionsPager: + r"""Deprecated: Use inline suggestion, event based suggestion or + Suggestion\* API instead. See + [HumanAgentAssistantConfig.name][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.name] + for more details. Removal Date: 2020-09-01. + + Retrieves suggestions for live agents. + + This method should be used by human agent client software to + fetch auto generated suggestions in real-time, while the + conversation with an end user is in progress. The functionality + is implemented in terms of the `list + pagination `__ + design pattern. The client app should use the + ``next_page_token`` field to fetch the next batch of + suggestions. ``suggestions`` are sorted by ``create_time`` in + descending order. To fetch latest suggestion, just set + ``page_size`` to 1. To fetch new suggestions without + duplication, send request with filter + ``create_time_epoch_microseconds > [first item's create_time of previous request]`` + and empty page_token. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListSuggestionsRequest, dict]): + The request object. The request message for + [Participants.ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.services.participants.pagers.ListSuggestionsPager: + The response message for + [Participants.ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + warnings.warn("ParticipantsClient.list_suggestions is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a participant.ListSuggestionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, participant.ListSuggestionsRequest): + request = participant.ListSuggestionsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_suggestions] + + # Certain 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.ListSuggestionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def compile_suggestion(self, + request: Union[participant.CompileSuggestionRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> participant.CompileSuggestionResponse: + r"""Deprecated. use + [SuggestArticles][google.cloud.dialogflow.v2beta1.Participants.SuggestArticles] + and + [SuggestFaqAnswers][google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers] + instead. + + Gets suggestions for a participant based on specific historical + messages. + + Note that + [ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions] + will only list the auto-generated suggestions, while + [CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion] + will try to compile suggestion based on the provided + conversation context in the real time. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.CompileSuggestionRequest, dict]): + The request object. The request message for + [Participants.CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.CompileSuggestionResponse: + The response message for + [Participants.CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion]. + + """ + warnings.warn("ParticipantsClient.compile_suggestion is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a participant.CompileSuggestionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, participant.CompileSuggestionRequest): + request = participant.CompileSuggestionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.compile_suggestion] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ParticipantsClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/pagers.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/pagers.py new file mode 100644 index 000000000..d2ba768be --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/pagers.py @@ -0,0 +1,262 @@ +# -*- 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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflow_v2beta1.types import participant + + +class ListParticipantsPager: + """A pager for iterating through ``list_participants`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListParticipantsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``participants`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListParticipants`` requests and continue to iterate + through the ``participants`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListParticipantsResponse` + 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[..., participant.ListParticipantsResponse], + request: participant.ListParticipantsRequest, + response: participant.ListParticipantsResponse, + *, + 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.dialogflow_v2beta1.types.ListParticipantsRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListParticipantsResponse): + 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 = participant.ListParticipantsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[participant.ListParticipantsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[participant.Participant]: + for page in self.pages: + yield from page.participants + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListParticipantsAsyncPager: + """A pager for iterating through ``list_participants`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListParticipantsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``participants`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListParticipants`` requests and continue to iterate + through the ``participants`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListParticipantsResponse` + 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[participant.ListParticipantsResponse]], + request: participant.ListParticipantsRequest, + response: participant.ListParticipantsResponse, + *, + 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.dialogflow_v2beta1.types.ListParticipantsRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListParticipantsResponse): + 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 = participant.ListParticipantsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[participant.ListParticipantsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[participant.Participant]: + async def async_generator(): + async for page in self.pages: + for response in page.participants: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSuggestionsPager: + """A pager for iterating through ``list_suggestions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListSuggestionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``suggestions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSuggestions`` requests and continue to iterate + through the ``suggestions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListSuggestionsResponse` + 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[..., participant.ListSuggestionsResponse], + request: participant.ListSuggestionsRequest, + response: participant.ListSuggestionsResponse, + *, + 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.dialogflow_v2beta1.types.ListSuggestionsRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListSuggestionsResponse): + 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 = participant.ListSuggestionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[participant.ListSuggestionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[participant.Suggestion]: + for page in self.pages: + yield from page.suggestions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSuggestionsAsyncPager: + """A pager for iterating through ``list_suggestions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListSuggestionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``suggestions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSuggestions`` requests and continue to iterate + through the ``suggestions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListSuggestionsResponse` + 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[participant.ListSuggestionsResponse]], + request: participant.ListSuggestionsRequest, + response: participant.ListSuggestionsResponse, + *, + 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.dialogflow_v2beta1.types.ListSuggestionsRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListSuggestionsResponse): + 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 = participant.ListSuggestionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[participant.ListSuggestionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[participant.Suggestion]: + async def async_generator(): + async for page in self.pages: + for response in page.suggestions: + 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/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/__init__.py new file mode 100644 index 000000000..e30c79b00 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/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 ParticipantsTransport +from .grpc import ParticipantsGrpcTransport +from .grpc_asyncio import ParticipantsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ParticipantsTransport]] +_transport_registry['grpc'] = ParticipantsGrpcTransport +_transport_registry['grpc_asyncio'] = ParticipantsGrpcAsyncIOTransport + +__all__ = ( + 'ParticipantsTransport', + 'ParticipantsGrpcTransport', + 'ParticipantsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/base.py new file mode 100644 index 000000000..1848c397d --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/base.py @@ -0,0 +1,280 @@ +# -*- 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.types import participant +from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ParticipantsTransport(abc.ABC): + """Abstract transport class for Participants.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_participant: gapic_v1.method.wrap_method( + self.create_participant, + default_timeout=None, + client_info=client_info, + ), + self.get_participant: gapic_v1.method.wrap_method( + self.get_participant, + default_timeout=None, + client_info=client_info, + ), + self.list_participants: gapic_v1.method.wrap_method( + self.list_participants, + default_timeout=None, + client_info=client_info, + ), + self.update_participant: gapic_v1.method.wrap_method( + self.update_participant, + default_timeout=None, + client_info=client_info, + ), + self.analyze_content: gapic_v1.method.wrap_method( + self.analyze_content, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=220.0, + ), + default_timeout=220.0, + client_info=client_info, + ), + self.suggest_articles: gapic_v1.method.wrap_method( + self.suggest_articles, + default_timeout=None, + client_info=client_info, + ), + self.suggest_faq_answers: gapic_v1.method.wrap_method( + self.suggest_faq_answers, + default_timeout=None, + client_info=client_info, + ), + self.suggest_smart_replies: gapic_v1.method.wrap_method( + self.suggest_smart_replies, + default_timeout=None, + client_info=client_info, + ), + self.list_suggestions: gapic_v1.method.wrap_method( + self.list_suggestions, + default_timeout=None, + client_info=client_info, + ), + self.compile_suggestion: gapic_v1.method.wrap_method( + self.compile_suggestion, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_participant(self) -> Callable[ + [gcd_participant.CreateParticipantRequest], + Union[ + gcd_participant.Participant, + Awaitable[gcd_participant.Participant] + ]]: + raise NotImplementedError() + + @property + def get_participant(self) -> Callable[ + [participant.GetParticipantRequest], + Union[ + participant.Participant, + Awaitable[participant.Participant] + ]]: + raise NotImplementedError() + + @property + def list_participants(self) -> Callable[ + [participant.ListParticipantsRequest], + Union[ + participant.ListParticipantsResponse, + Awaitable[participant.ListParticipantsResponse] + ]]: + raise NotImplementedError() + + @property + def update_participant(self) -> Callable[ + [gcd_participant.UpdateParticipantRequest], + Union[ + gcd_participant.Participant, + Awaitable[gcd_participant.Participant] + ]]: + raise NotImplementedError() + + @property + def analyze_content(self) -> Callable[ + [gcd_participant.AnalyzeContentRequest], + Union[ + gcd_participant.AnalyzeContentResponse, + Awaitable[gcd_participant.AnalyzeContentResponse] + ]]: + raise NotImplementedError() + + @property + def suggest_articles(self) -> Callable[ + [participant.SuggestArticlesRequest], + Union[ + participant.SuggestArticlesResponse, + Awaitable[participant.SuggestArticlesResponse] + ]]: + raise NotImplementedError() + + @property + def suggest_faq_answers(self) -> Callable[ + [participant.SuggestFaqAnswersRequest], + Union[ + participant.SuggestFaqAnswersResponse, + Awaitable[participant.SuggestFaqAnswersResponse] + ]]: + raise NotImplementedError() + + @property + def suggest_smart_replies(self) -> Callable[ + [participant.SuggestSmartRepliesRequest], + Union[ + participant.SuggestSmartRepliesResponse, + Awaitable[participant.SuggestSmartRepliesResponse] + ]]: + raise NotImplementedError() + + @property + def list_suggestions(self) -> Callable[ + [participant.ListSuggestionsRequest], + Union[ + participant.ListSuggestionsResponse, + Awaitable[participant.ListSuggestionsResponse] + ]]: + raise NotImplementedError() + + @property + def compile_suggestion(self) -> Callable[ + [participant.CompileSuggestionRequest], + Union[ + participant.CompileSuggestionResponse, + Awaitable[participant.CompileSuggestionResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'ParticipantsTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc.py new file mode 100644 index 000000000..5ddb39358 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc.py @@ -0,0 +1,539 @@ +# -*- 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 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import participant +from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant +from .base import ParticipantsTransport, DEFAULT_CLIENT_INFO + + +class ParticipantsGrpcTransport(ParticipantsTransport): + """gRPC backend transport for Participants. + + Service for managing + [Participants][google.cloud.dialogflow.v2beta1.Participant]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 = 'dialogflow.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_participant(self) -> Callable[ + [gcd_participant.CreateParticipantRequest], + gcd_participant.Participant]: + r"""Return a callable for the create participant method over gRPC. + + Creates a new participant in a conversation. + + Returns: + Callable[[~.CreateParticipantRequest], + ~.Participant]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_participant' not in self._stubs: + self._stubs['create_participant'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Participants/CreateParticipant', + request_serializer=gcd_participant.CreateParticipantRequest.serialize, + response_deserializer=gcd_participant.Participant.deserialize, + ) + return self._stubs['create_participant'] + + @property + def get_participant(self) -> Callable[ + [participant.GetParticipantRequest], + participant.Participant]: + r"""Return a callable for the get participant method over gRPC. + + Retrieves a conversation participant. + + Returns: + Callable[[~.GetParticipantRequest], + ~.Participant]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_participant' not in self._stubs: + self._stubs['get_participant'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Participants/GetParticipant', + request_serializer=participant.GetParticipantRequest.serialize, + response_deserializer=participant.Participant.deserialize, + ) + return self._stubs['get_participant'] + + @property + def list_participants(self) -> Callable[ + [participant.ListParticipantsRequest], + participant.ListParticipantsResponse]: + r"""Return a callable for the list participants method over gRPC. + + Returns the list of all participants in the specified + conversation. + + Returns: + Callable[[~.ListParticipantsRequest], + ~.ListParticipantsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_participants' not in self._stubs: + self._stubs['list_participants'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Participants/ListParticipants', + request_serializer=participant.ListParticipantsRequest.serialize, + response_deserializer=participant.ListParticipantsResponse.deserialize, + ) + return self._stubs['list_participants'] + + @property + def update_participant(self) -> Callable[ + [gcd_participant.UpdateParticipantRequest], + gcd_participant.Participant]: + r"""Return a callable for the update participant method over gRPC. + + Updates the specified participant. + + Returns: + Callable[[~.UpdateParticipantRequest], + ~.Participant]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_participant' not in self._stubs: + self._stubs['update_participant'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Participants/UpdateParticipant', + request_serializer=gcd_participant.UpdateParticipantRequest.serialize, + response_deserializer=gcd_participant.Participant.deserialize, + ) + return self._stubs['update_participant'] + + @property + def analyze_content(self) -> Callable[ + [gcd_participant.AnalyzeContentRequest], + gcd_participant.AnalyzeContentResponse]: + r"""Return a callable for the analyze content method over gRPC. + + Adds a text (chat, for example), or audio (phone recording, for + example) message from a participant into the conversation. + + Note: Always use agent versions for production traffic sent to + virtual agents. See `Versions and + environments `__. + + Returns: + Callable[[~.AnalyzeContentRequest], + ~.AnalyzeContentResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'analyze_content' not in self._stubs: + self._stubs['analyze_content'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Participants/AnalyzeContent', + request_serializer=gcd_participant.AnalyzeContentRequest.serialize, + response_deserializer=gcd_participant.AnalyzeContentResponse.deserialize, + ) + return self._stubs['analyze_content'] + + @property + def suggest_articles(self) -> Callable[ + [participant.SuggestArticlesRequest], + participant.SuggestArticlesResponse]: + r"""Return a callable for the suggest articles method over gRPC. + + Gets suggested articles for a participant based on specific + historical messages. + + Note that + [ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions] + will only list the auto-generated suggestions, while + [CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion] + will try to compile suggestion based on the provided + conversation context in the real time. + + Returns: + Callable[[~.SuggestArticlesRequest], + ~.SuggestArticlesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'suggest_articles' not in self._stubs: + self._stubs['suggest_articles'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Participants/SuggestArticles', + request_serializer=participant.SuggestArticlesRequest.serialize, + response_deserializer=participant.SuggestArticlesResponse.deserialize, + ) + return self._stubs['suggest_articles'] + + @property + def suggest_faq_answers(self) -> Callable[ + [participant.SuggestFaqAnswersRequest], + participant.SuggestFaqAnswersResponse]: + r"""Return a callable for the suggest faq answers method over gRPC. + + Gets suggested faq answers for a participant based on + specific historical messages. + + Returns: + Callable[[~.SuggestFaqAnswersRequest], + ~.SuggestFaqAnswersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'suggest_faq_answers' not in self._stubs: + self._stubs['suggest_faq_answers'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Participants/SuggestFaqAnswers', + request_serializer=participant.SuggestFaqAnswersRequest.serialize, + response_deserializer=participant.SuggestFaqAnswersResponse.deserialize, + ) + return self._stubs['suggest_faq_answers'] + + @property + def suggest_smart_replies(self) -> Callable[ + [participant.SuggestSmartRepliesRequest], + participant.SuggestSmartRepliesResponse]: + r"""Return a callable for the suggest smart replies method over gRPC. + + Gets smart replies for a participant based on + specific historical messages. + + Returns: + Callable[[~.SuggestSmartRepliesRequest], + ~.SuggestSmartRepliesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'suggest_smart_replies' not in self._stubs: + self._stubs['suggest_smart_replies'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Participants/SuggestSmartReplies', + request_serializer=participant.SuggestSmartRepliesRequest.serialize, + response_deserializer=participant.SuggestSmartRepliesResponse.deserialize, + ) + return self._stubs['suggest_smart_replies'] + + @property + def list_suggestions(self) -> Callable[ + [participant.ListSuggestionsRequest], + participant.ListSuggestionsResponse]: + r"""Return a callable for the list suggestions method over gRPC. + + Deprecated: Use inline suggestion, event based suggestion or + Suggestion\* API instead. See + [HumanAgentAssistantConfig.name][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.name] + for more details. Removal Date: 2020-09-01. + + Retrieves suggestions for live agents. + + This method should be used by human agent client software to + fetch auto generated suggestions in real-time, while the + conversation with an end user is in progress. The functionality + is implemented in terms of the `list + pagination `__ + design pattern. The client app should use the + ``next_page_token`` field to fetch the next batch of + suggestions. ``suggestions`` are sorted by ``create_time`` in + descending order. To fetch latest suggestion, just set + ``page_size`` to 1. To fetch new suggestions without + duplication, send request with filter + ``create_time_epoch_microseconds > [first item's create_time of previous request]`` + and empty page_token. + + Returns: + Callable[[~.ListSuggestionsRequest], + ~.ListSuggestionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_suggestions' not in self._stubs: + self._stubs['list_suggestions'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Participants/ListSuggestions', + request_serializer=participant.ListSuggestionsRequest.serialize, + response_deserializer=participant.ListSuggestionsResponse.deserialize, + ) + return self._stubs['list_suggestions'] + + @property + def compile_suggestion(self) -> Callable[ + [participant.CompileSuggestionRequest], + participant.CompileSuggestionResponse]: + r"""Return a callable for the compile suggestion method over gRPC. + + Deprecated. use + [SuggestArticles][google.cloud.dialogflow.v2beta1.Participants.SuggestArticles] + and + [SuggestFaqAnswers][google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers] + instead. + + Gets suggestions for a participant based on specific historical + messages. + + Note that + [ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions] + will only list the auto-generated suggestions, while + [CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion] + will try to compile suggestion based on the provided + conversation context in the real time. + + Returns: + Callable[[~.CompileSuggestionRequest], + ~.CompileSuggestionResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'compile_suggestion' not in self._stubs: + self._stubs['compile_suggestion'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Participants/CompileSuggestion', + request_serializer=participant.CompileSuggestionRequest.serialize, + response_deserializer=participant.CompileSuggestionResponse.deserialize, + ) + return self._stubs['compile_suggestion'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'ParticipantsGrpcTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc_asyncio.py new file mode 100644 index 000000000..8f1d900df --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc_asyncio.py @@ -0,0 +1,543 @@ +# -*- 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 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import participant +from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant +from .base import ParticipantsTransport, DEFAULT_CLIENT_INFO +from .grpc import ParticipantsGrpcTransport + + +class ParticipantsGrpcAsyncIOTransport(ParticipantsTransport): + """gRPC AsyncIO backend transport for Participants. + + Service for managing + [Participants][google.cloud.dialogflow.v2beta1.Participant]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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_participant(self) -> Callable[ + [gcd_participant.CreateParticipantRequest], + Awaitable[gcd_participant.Participant]]: + r"""Return a callable for the create participant method over gRPC. + + Creates a new participant in a conversation. + + Returns: + Callable[[~.CreateParticipantRequest], + Awaitable[~.Participant]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_participant' not in self._stubs: + self._stubs['create_participant'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Participants/CreateParticipant', + request_serializer=gcd_participant.CreateParticipantRequest.serialize, + response_deserializer=gcd_participant.Participant.deserialize, + ) + return self._stubs['create_participant'] + + @property + def get_participant(self) -> Callable[ + [participant.GetParticipantRequest], + Awaitable[participant.Participant]]: + r"""Return a callable for the get participant method over gRPC. + + Retrieves a conversation participant. + + Returns: + Callable[[~.GetParticipantRequest], + Awaitable[~.Participant]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_participant' not in self._stubs: + self._stubs['get_participant'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Participants/GetParticipant', + request_serializer=participant.GetParticipantRequest.serialize, + response_deserializer=participant.Participant.deserialize, + ) + return self._stubs['get_participant'] + + @property + def list_participants(self) -> Callable[ + [participant.ListParticipantsRequest], + Awaitable[participant.ListParticipantsResponse]]: + r"""Return a callable for the list participants method over gRPC. + + Returns the list of all participants in the specified + conversation. + + Returns: + Callable[[~.ListParticipantsRequest], + Awaitable[~.ListParticipantsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_participants' not in self._stubs: + self._stubs['list_participants'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Participants/ListParticipants', + request_serializer=participant.ListParticipantsRequest.serialize, + response_deserializer=participant.ListParticipantsResponse.deserialize, + ) + return self._stubs['list_participants'] + + @property + def update_participant(self) -> Callable[ + [gcd_participant.UpdateParticipantRequest], + Awaitable[gcd_participant.Participant]]: + r"""Return a callable for the update participant method over gRPC. + + Updates the specified participant. + + Returns: + Callable[[~.UpdateParticipantRequest], + Awaitable[~.Participant]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_participant' not in self._stubs: + self._stubs['update_participant'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Participants/UpdateParticipant', + request_serializer=gcd_participant.UpdateParticipantRequest.serialize, + response_deserializer=gcd_participant.Participant.deserialize, + ) + return self._stubs['update_participant'] + + @property + def analyze_content(self) -> Callable[ + [gcd_participant.AnalyzeContentRequest], + Awaitable[gcd_participant.AnalyzeContentResponse]]: + r"""Return a callable for the analyze content method over gRPC. + + Adds a text (chat, for example), or audio (phone recording, for + example) message from a participant into the conversation. + + Note: Always use agent versions for production traffic sent to + virtual agents. See `Versions and + environments `__. + + Returns: + Callable[[~.AnalyzeContentRequest], + Awaitable[~.AnalyzeContentResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'analyze_content' not in self._stubs: + self._stubs['analyze_content'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Participants/AnalyzeContent', + request_serializer=gcd_participant.AnalyzeContentRequest.serialize, + response_deserializer=gcd_participant.AnalyzeContentResponse.deserialize, + ) + return self._stubs['analyze_content'] + + @property + def suggest_articles(self) -> Callable[ + [participant.SuggestArticlesRequest], + Awaitable[participant.SuggestArticlesResponse]]: + r"""Return a callable for the suggest articles method over gRPC. + + Gets suggested articles for a participant based on specific + historical messages. + + Note that + [ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions] + will only list the auto-generated suggestions, while + [CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion] + will try to compile suggestion based on the provided + conversation context in the real time. + + Returns: + Callable[[~.SuggestArticlesRequest], + Awaitable[~.SuggestArticlesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'suggest_articles' not in self._stubs: + self._stubs['suggest_articles'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Participants/SuggestArticles', + request_serializer=participant.SuggestArticlesRequest.serialize, + response_deserializer=participant.SuggestArticlesResponse.deserialize, + ) + return self._stubs['suggest_articles'] + + @property + def suggest_faq_answers(self) -> Callable[ + [participant.SuggestFaqAnswersRequest], + Awaitable[participant.SuggestFaqAnswersResponse]]: + r"""Return a callable for the suggest faq answers method over gRPC. + + Gets suggested faq answers for a participant based on + specific historical messages. + + Returns: + Callable[[~.SuggestFaqAnswersRequest], + Awaitable[~.SuggestFaqAnswersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'suggest_faq_answers' not in self._stubs: + self._stubs['suggest_faq_answers'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Participants/SuggestFaqAnswers', + request_serializer=participant.SuggestFaqAnswersRequest.serialize, + response_deserializer=participant.SuggestFaqAnswersResponse.deserialize, + ) + return self._stubs['suggest_faq_answers'] + + @property + def suggest_smart_replies(self) -> Callable[ + [participant.SuggestSmartRepliesRequest], + Awaitable[participant.SuggestSmartRepliesResponse]]: + r"""Return a callable for the suggest smart replies method over gRPC. + + Gets smart replies for a participant based on + specific historical messages. + + Returns: + Callable[[~.SuggestSmartRepliesRequest], + Awaitable[~.SuggestSmartRepliesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'suggest_smart_replies' not in self._stubs: + self._stubs['suggest_smart_replies'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Participants/SuggestSmartReplies', + request_serializer=participant.SuggestSmartRepliesRequest.serialize, + response_deserializer=participant.SuggestSmartRepliesResponse.deserialize, + ) + return self._stubs['suggest_smart_replies'] + + @property + def list_suggestions(self) -> Callable[ + [participant.ListSuggestionsRequest], + Awaitable[participant.ListSuggestionsResponse]]: + r"""Return a callable for the list suggestions method over gRPC. + + Deprecated: Use inline suggestion, event based suggestion or + Suggestion\* API instead. See + [HumanAgentAssistantConfig.name][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.name] + for more details. Removal Date: 2020-09-01. + + Retrieves suggestions for live agents. + + This method should be used by human agent client software to + fetch auto generated suggestions in real-time, while the + conversation with an end user is in progress. The functionality + is implemented in terms of the `list + pagination `__ + design pattern. The client app should use the + ``next_page_token`` field to fetch the next batch of + suggestions. ``suggestions`` are sorted by ``create_time`` in + descending order. To fetch latest suggestion, just set + ``page_size`` to 1. To fetch new suggestions without + duplication, send request with filter + ``create_time_epoch_microseconds > [first item's create_time of previous request]`` + and empty page_token. + + Returns: + Callable[[~.ListSuggestionsRequest], + Awaitable[~.ListSuggestionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_suggestions' not in self._stubs: + self._stubs['list_suggestions'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Participants/ListSuggestions', + request_serializer=participant.ListSuggestionsRequest.serialize, + response_deserializer=participant.ListSuggestionsResponse.deserialize, + ) + return self._stubs['list_suggestions'] + + @property + def compile_suggestion(self) -> Callable[ + [participant.CompileSuggestionRequest], + Awaitable[participant.CompileSuggestionResponse]]: + r"""Return a callable for the compile suggestion method over gRPC. + + Deprecated. use + [SuggestArticles][google.cloud.dialogflow.v2beta1.Participants.SuggestArticles] + and + [SuggestFaqAnswers][google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers] + instead. + + Gets suggestions for a participant based on specific historical + messages. + + Note that + [ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions] + will only list the auto-generated suggestions, while + [CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion] + will try to compile suggestion based on the provided + conversation context in the real time. + + Returns: + Callable[[~.CompileSuggestionRequest], + Awaitable[~.CompileSuggestionResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'compile_suggestion' not in self._stubs: + self._stubs['compile_suggestion'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Participants/CompileSuggestion', + request_serializer=participant.CompileSuggestionRequest.serialize, + response_deserializer=participant.CompileSuggestionResponse.deserialize, + ) + return self._stubs['compile_suggestion'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ParticipantsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/__init__.py new file mode 100644 index 000000000..fb6678b14 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/__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 SessionEntityTypesClient +from .async_client import SessionEntityTypesAsyncClient + +__all__ = ( + 'SessionEntityTypesClient', + 'SessionEntityTypesAsyncClient', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/async_client.py new file mode 100644 index 000000000..15f0f5bd1 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/async_client.py @@ -0,0 +1,656 @@ +# -*- 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 + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2beta1.services.session_entity_types import pagers +from google.cloud.dialogflow_v2beta1.types import entity_type +from google.cloud.dialogflow_v2beta1.types import session_entity_type +from google.cloud.dialogflow_v2beta1.types import session_entity_type as gcd_session_entity_type +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SessionEntityTypesGrpcAsyncIOTransport +from .client import SessionEntityTypesClient + + +class SessionEntityTypesAsyncClient: + """Service for managing + [SessionEntityTypes][google.cloud.dialogflow.v2beta1.SessionEntityType]. + """ + + _client: SessionEntityTypesClient + + DEFAULT_ENDPOINT = SessionEntityTypesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SessionEntityTypesClient.DEFAULT_MTLS_ENDPOINT + + session_entity_type_path = staticmethod(SessionEntityTypesClient.session_entity_type_path) + parse_session_entity_type_path = staticmethod(SessionEntityTypesClient.parse_session_entity_type_path) + common_billing_account_path = staticmethod(SessionEntityTypesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SessionEntityTypesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SessionEntityTypesClient.common_folder_path) + parse_common_folder_path = staticmethod(SessionEntityTypesClient.parse_common_folder_path) + common_organization_path = staticmethod(SessionEntityTypesClient.common_organization_path) + parse_common_organization_path = staticmethod(SessionEntityTypesClient.parse_common_organization_path) + common_project_path = staticmethod(SessionEntityTypesClient.common_project_path) + parse_common_project_path = staticmethod(SessionEntityTypesClient.parse_common_project_path) + common_location_path = staticmethod(SessionEntityTypesClient.common_location_path) + parse_common_location_path = staticmethod(SessionEntityTypesClient.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: + SessionEntityTypesAsyncClient: The constructed client. + """ + return SessionEntityTypesClient.from_service_account_info.__func__(SessionEntityTypesAsyncClient, 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: + SessionEntityTypesAsyncClient: The constructed client. + """ + return SessionEntityTypesClient.from_service_account_file.__func__(SessionEntityTypesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SessionEntityTypesTransport: + """Returns the transport used by the client instance. + + Returns: + SessionEntityTypesTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SessionEntityTypesClient).get_transport_class, type(SessionEntityTypesClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, SessionEntityTypesTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the session entity types 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, ~.SessionEntityTypesTransport]): 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 = SessionEntityTypesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_session_entity_types(self, + request: Union[session_entity_type.ListSessionEntityTypesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSessionEntityTypesAsyncPager: + r"""Returns the list of all session entity types in the + specified session. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListSessionEntityTypesRequest, dict]): + The request object. The request message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2beta1.SessionEntityTypes.ListSessionEntityTypes]. + parent (:class:`str`): + Required. The session to list all session entity types + from. Supported formats: + + - \`projects//agent/sessions/, + - ``projects//locations//agent/sessions/``, + - ``projects//agent/environments//users//sessions/``, + - ``projects//locations//agent/environments//users//sessions/``, + + If ``Location ID`` is not specified we assume default + 'us' location. If ``Environment ID`` is not specified, + we assume default 'draft' environment. If ``User ID`` is + not specified, we assume default '-' user. + + 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.dialogflow_v2beta1.services.session_entity_types.pagers.ListSessionEntityTypesAsyncPager: + The response message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2beta1.SessionEntityTypes.ListSessionEntityTypes]. + + 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 = session_entity_type.ListSessionEntityTypesRequest(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_session_entity_types, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSessionEntityTypesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_session_entity_type(self, + request: Union[session_entity_type.GetSessionEntityTypeRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> session_entity_type.SessionEntityType: + r"""Retrieves the specified session entity type. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetSessionEntityTypeRequest, dict]): + The request object. The request message for + [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.GetSessionEntityType]. + name (:class:`str`): + Required. The name of the session entity type. Supported + formats: + + - ``projects//agent/sessions//entityTypes/`` + - ``projects//locations//agent/sessions//entityTypes/`` + - ``projects//agent/environments//users//sessions//entityTypes/`` + - ``projects//locations//agent/environments/ /users//sessions//entityTypes/`` + + If ``Location ID`` is not specified we assume default + 'us' location. If ``Environment ID`` is not specified, + we assume default 'draft' environment. If ``User ID`` is + not specified, we assume default '-' user. + + 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.dialogflow_v2beta1.types.SessionEntityType: + A session represents a conversation between a Dialogflow agent and an + end-user. You can create special entities, called + session entities, during a session. Session entities + can extend or replace custom entity types and only + exist during the session that they were created for. + All session data, including session entities, is + stored by Dialogflow for 20 minutes. + + For more information, see the [session entity + guide](\ https://cloud.google.com/dialogflow/docs/entities-session). + + """ + # 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 = session_entity_type.GetSessionEntityTypeRequest(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_session_entity_type, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_session_entity_type(self, + request: Union[gcd_session_entity_type.CreateSessionEntityTypeRequest, dict] = None, + *, + parent: str = None, + session_entity_type: gcd_session_entity_type.SessionEntityType = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_session_entity_type.SessionEntityType: + r"""Creates a session entity type. + If the specified session entity type already exists, + overrides the session entity type. + + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.CreateSessionEntityTypeRequest, dict]): + The request object. The request message for + [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.CreateSessionEntityType]. + parent (:class:`str`): + Required. The session to create a session entity type + for. Supported formats: + + - \`projects//agent/sessions/, + - ``projects//locations//agent/sessions/``, + - ``projects//agent/environments//users//sessions/``, + - ``projects//locations//agent/environments//users//sessions/``, + + If ``Location ID`` is not specified we assume default + 'us' location. If ``Environment ID`` is not specified, + we assume default 'draft' environment. If ``User ID`` is + not specified, we assume default '-' user. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + session_entity_type (:class:`google.cloud.dialogflow_v2beta1.types.SessionEntityType`): + Required. The session entity type to + create. + + This corresponds to the ``session_entity_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.SessionEntityType: + A session represents a conversation between a Dialogflow agent and an + end-user. You can create special entities, called + session entities, during a session. Session entities + can extend or replace custom entity types and only + exist during the session that they were created for. + All session data, including session entities, is + stored by Dialogflow for 20 minutes. + + For more information, see the [session entity + guide](\ https://cloud.google.com/dialogflow/docs/entities-session). + + """ + # 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, session_entity_type]) + if request is 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 = gcd_session_entity_type.CreateSessionEntityTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if session_entity_type is not None: + request.session_entity_type = session_entity_type + + # 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_session_entity_type, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_session_entity_type(self, + request: Union[gcd_session_entity_type.UpdateSessionEntityTypeRequest, dict] = None, + *, + session_entity_type: gcd_session_entity_type.SessionEntityType = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_session_entity_type.SessionEntityType: + r"""Updates the specified session entity type. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.UpdateSessionEntityTypeRequest, dict]): + The request object. The request message for + [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.UpdateSessionEntityType]. + session_entity_type (:class:`google.cloud.dialogflow_v2beta1.types.SessionEntityType`): + Required. The session entity type to + update. + + This corresponds to the ``session_entity_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.SessionEntityType: + A session represents a conversation between a Dialogflow agent and an + end-user. You can create special entities, called + session entities, during a session. Session entities + can extend or replace custom entity types and only + exist during the session that they were created for. + All session data, including session entities, is + stored by Dialogflow for 20 minutes. + + For more information, see the [session entity + guide](\ https://cloud.google.com/dialogflow/docs/entities-session). + + """ + # 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([session_entity_type, 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 = gcd_session_entity_type.UpdateSessionEntityTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if session_entity_type is not None: + request.session_entity_type = session_entity_type + 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_session_entity_type, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("session_entity_type.name", request.session_entity_type.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_session_entity_type(self, + request: Union[session_entity_type.DeleteSessionEntityTypeRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified session entity type. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.DeleteSessionEntityTypeRequest, dict]): + The request object. The request message for + [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.DeleteSessionEntityType]. + name (:class:`str`): + Required. The name of the entity type to delete. + Supported formats: + + - ``projects//agent/sessions//entityTypes/`` + - ``projects//locations//agent/sessions//entityTypes/`` + - ``projects//agent/environments//users//sessions//entityTypes/`` + - ``projects//locations//agent/environments/ /users//sessions//entityTypes/`` + + If ``Location ID`` is not specified we assume default + 'us' location. If ``Environment ID`` is not specified, + we assume default 'draft' environment. If ``User ID`` is + not specified, we assume default '-' user. + + 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 = session_entity_type.DeleteSessionEntityTypeRequest(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_session_entity_type, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SessionEntityTypesAsyncClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/client.py new file mode 100644 index 000000000..073153927 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/client.py @@ -0,0 +1,854 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2beta1.services.session_entity_types import pagers +from google.cloud.dialogflow_v2beta1.types import entity_type +from google.cloud.dialogflow_v2beta1.types import session_entity_type +from google.cloud.dialogflow_v2beta1.types import session_entity_type as gcd_session_entity_type +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SessionEntityTypesGrpcTransport +from .transports.grpc_asyncio import SessionEntityTypesGrpcAsyncIOTransport + + +class SessionEntityTypesClientMeta(type): + """Metaclass for the SessionEntityTypes 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[SessionEntityTypesTransport]] + _transport_registry["grpc"] = SessionEntityTypesGrpcTransport + _transport_registry["grpc_asyncio"] = SessionEntityTypesGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[SessionEntityTypesTransport]: + """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 SessionEntityTypesClient(metaclass=SessionEntityTypesClientMeta): + """Service for managing + [SessionEntityTypes][google.cloud.dialogflow.v2beta1.SessionEntityType]. + """ + + @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 = "dialogflow.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: + SessionEntityTypesClient: 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: + SessionEntityTypesClient: 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) -> SessionEntityTypesTransport: + """Returns the transport used by the client instance. + + Returns: + SessionEntityTypesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def session_entity_type_path(project: str,session: str,entity_type: str,) -> str: + """Returns a fully-qualified session_entity_type string.""" + return "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format(project=project, session=session, entity_type=entity_type, ) + + @staticmethod + def parse_session_entity_type_path(path: str) -> Dict[str,str]: + """Parses a session_entity_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/entityTypes/(?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, SessionEntityTypesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the session entity types 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, SessionEntityTypesTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, SessionEntityTypesTransport): + # transport is a SessionEntityTypesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_session_entity_types(self, + request: Union[session_entity_type.ListSessionEntityTypesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSessionEntityTypesPager: + r"""Returns the list of all session entity types in the + specified session. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListSessionEntityTypesRequest, dict]): + The request object. The request message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2beta1.SessionEntityTypes.ListSessionEntityTypes]. + parent (str): + Required. The session to list all session entity types + from. Supported formats: + + - \`projects//agent/sessions/, + - ``projects//locations//agent/sessions/``, + - ``projects//agent/environments//users//sessions/``, + - ``projects//locations//agent/environments//users//sessions/``, + + If ``Location ID`` is not specified we assume default + 'us' location. If ``Environment ID`` is not specified, + we assume default 'draft' environment. If ``User ID`` is + not specified, we assume default '-' user. + + 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.dialogflow_v2beta1.services.session_entity_types.pagers.ListSessionEntityTypesPager: + The response message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2beta1.SessionEntityTypes.ListSessionEntityTypes]. + + 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 session_entity_type.ListSessionEntityTypesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, session_entity_type.ListSessionEntityTypesRequest): + request = session_entity_type.ListSessionEntityTypesRequest(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_session_entity_types] + + # Certain 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.ListSessionEntityTypesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_session_entity_type(self, + request: Union[session_entity_type.GetSessionEntityTypeRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> session_entity_type.SessionEntityType: + r"""Retrieves the specified session entity type. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetSessionEntityTypeRequest, dict]): + The request object. The request message for + [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.GetSessionEntityType]. + name (str): + Required. The name of the session entity type. Supported + formats: + + - ``projects//agent/sessions//entityTypes/`` + - ``projects//locations//agent/sessions//entityTypes/`` + - ``projects//agent/environments//users//sessions//entityTypes/`` + - ``projects//locations//agent/environments/ /users//sessions//entityTypes/`` + + If ``Location ID`` is not specified we assume default + 'us' location. If ``Environment ID`` is not specified, + we assume default 'draft' environment. If ``User ID`` is + not specified, we assume default '-' user. + + 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.dialogflow_v2beta1.types.SessionEntityType: + A session represents a conversation between a Dialogflow agent and an + end-user. You can create special entities, called + session entities, during a session. Session entities + can extend or replace custom entity types and only + exist during the session that they were created for. + All session data, including session entities, is + stored by Dialogflow for 20 minutes. + + For more information, see the [session entity + guide](\ https://cloud.google.com/dialogflow/docs/entities-session). + + """ + # 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 session_entity_type.GetSessionEntityTypeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, session_entity_type.GetSessionEntityTypeRequest): + request = session_entity_type.GetSessionEntityTypeRequest(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_session_entity_type] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_session_entity_type(self, + request: Union[gcd_session_entity_type.CreateSessionEntityTypeRequest, dict] = None, + *, + parent: str = None, + session_entity_type: gcd_session_entity_type.SessionEntityType = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_session_entity_type.SessionEntityType: + r"""Creates a session entity type. + If the specified session entity type already exists, + overrides the session entity type. + + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.CreateSessionEntityTypeRequest, dict]): + The request object. The request message for + [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.CreateSessionEntityType]. + parent (str): + Required. The session to create a session entity type + for. Supported formats: + + - \`projects//agent/sessions/, + - ``projects//locations//agent/sessions/``, + - ``projects//agent/environments//users//sessions/``, + - ``projects//locations//agent/environments//users//sessions/``, + + If ``Location ID`` is not specified we assume default + 'us' location. If ``Environment ID`` is not specified, + we assume default 'draft' environment. If ``User ID`` is + not specified, we assume default '-' user. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + session_entity_type (google.cloud.dialogflow_v2beta1.types.SessionEntityType): + Required. The session entity type to + create. + + This corresponds to the ``session_entity_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.SessionEntityType: + A session represents a conversation between a Dialogflow agent and an + end-user. You can create special entities, called + session entities, during a session. Session entities + can extend or replace custom entity types and only + exist during the session that they were created for. + All session data, including session entities, is + stored by Dialogflow for 20 minutes. + + For more information, see the [session entity + guide](\ https://cloud.google.com/dialogflow/docs/entities-session). + + """ + # 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, session_entity_type]) + if request is 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 gcd_session_entity_type.CreateSessionEntityTypeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_session_entity_type.CreateSessionEntityTypeRequest): + request = gcd_session_entity_type.CreateSessionEntityTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if session_entity_type is not None: + request.session_entity_type = session_entity_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_session_entity_type] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_session_entity_type(self, + request: Union[gcd_session_entity_type.UpdateSessionEntityTypeRequest, dict] = None, + *, + session_entity_type: gcd_session_entity_type.SessionEntityType = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_session_entity_type.SessionEntityType: + r"""Updates the specified session entity type. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.UpdateSessionEntityTypeRequest, dict]): + The request object. The request message for + [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.UpdateSessionEntityType]. + session_entity_type (google.cloud.dialogflow_v2beta1.types.SessionEntityType): + Required. The session entity type to + update. + + This corresponds to the ``session_entity_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.SessionEntityType: + A session represents a conversation between a Dialogflow agent and an + end-user. You can create special entities, called + session entities, during a session. Session entities + can extend or replace custom entity types and only + exist during the session that they were created for. + All session data, including session entities, is + stored by Dialogflow for 20 minutes. + + For more information, see the [session entity + guide](\ https://cloud.google.com/dialogflow/docs/entities-session). + + """ + # 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([session_entity_type, 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 gcd_session_entity_type.UpdateSessionEntityTypeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_session_entity_type.UpdateSessionEntityTypeRequest): + request = gcd_session_entity_type.UpdateSessionEntityTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if session_entity_type is not None: + request.session_entity_type = session_entity_type + 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_session_entity_type] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("session_entity_type.name", request.session_entity_type.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_session_entity_type(self, + request: Union[session_entity_type.DeleteSessionEntityTypeRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified session entity type. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.DeleteSessionEntityTypeRequest, dict]): + The request object. The request message for + [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.DeleteSessionEntityType]. + name (str): + Required. The name of the entity type to delete. + Supported formats: + + - ``projects//agent/sessions//entityTypes/`` + - ``projects//locations//agent/sessions//entityTypes/`` + - ``projects//agent/environments//users//sessions//entityTypes/`` + - ``projects//locations//agent/environments/ /users//sessions//entityTypes/`` + + If ``Location ID`` is not specified we assume default + 'us' location. If ``Environment ID`` is not specified, + we assume default 'draft' environment. If ``User ID`` is + not specified, we assume default '-' user. + + 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 session_entity_type.DeleteSessionEntityTypeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, session_entity_type.DeleteSessionEntityTypeRequest): + request = session_entity_type.DeleteSessionEntityTypeRequest(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_session_entity_type] + + # Certain 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 __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SessionEntityTypesClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/pagers.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/pagers.py new file mode 100644 index 000000000..9d3d31349 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflow_v2beta1.types import session_entity_type + + +class ListSessionEntityTypesPager: + """A pager for iterating through ``list_session_entity_types`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListSessionEntityTypesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``session_entity_types`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSessionEntityTypes`` requests and continue to iterate + through the ``session_entity_types`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListSessionEntityTypesResponse` + 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[..., session_entity_type.ListSessionEntityTypesResponse], + request: session_entity_type.ListSessionEntityTypesRequest, + response: session_entity_type.ListSessionEntityTypesResponse, + *, + 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.dialogflow_v2beta1.types.ListSessionEntityTypesRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListSessionEntityTypesResponse): + 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 = session_entity_type.ListSessionEntityTypesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[session_entity_type.ListSessionEntityTypesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[session_entity_type.SessionEntityType]: + for page in self.pages: + yield from page.session_entity_types + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSessionEntityTypesAsyncPager: + """A pager for iterating through ``list_session_entity_types`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListSessionEntityTypesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``session_entity_types`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSessionEntityTypes`` requests and continue to iterate + through the ``session_entity_types`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListSessionEntityTypesResponse` + 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[session_entity_type.ListSessionEntityTypesResponse]], + request: session_entity_type.ListSessionEntityTypesRequest, + response: session_entity_type.ListSessionEntityTypesResponse, + *, + 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.dialogflow_v2beta1.types.ListSessionEntityTypesRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListSessionEntityTypesResponse): + 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 = session_entity_type.ListSessionEntityTypesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[session_entity_type.ListSessionEntityTypesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[session_entity_type.SessionEntityType]: + async def async_generator(): + async for page in self.pages: + for response in page.session_entity_types: + 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/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/__init__.py new file mode 100644 index 000000000..fee526724 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/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 SessionEntityTypesTransport +from .grpc import SessionEntityTypesGrpcTransport +from .grpc_asyncio import SessionEntityTypesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SessionEntityTypesTransport]] +_transport_registry['grpc'] = SessionEntityTypesGrpcTransport +_transport_registry['grpc_asyncio'] = SessionEntityTypesGrpcAsyncIOTransport + +__all__ = ( + 'SessionEntityTypesTransport', + 'SessionEntityTypesGrpcTransport', + 'SessionEntityTypesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/base.py new file mode 100644 index 000000000..761d8e72f --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/base.py @@ -0,0 +1,205 @@ +# -*- 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.types import session_entity_type +from google.cloud.dialogflow_v2beta1.types import session_entity_type as gcd_session_entity_type +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-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class SessionEntityTypesTransport(abc.ABC): + """Abstract transport class for SessionEntityTypes.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_session_entity_types: gapic_v1.method.wrap_method( + self.list_session_entity_types, + default_timeout=None, + client_info=client_info, + ), + self.get_session_entity_type: gapic_v1.method.wrap_method( + self.get_session_entity_type, + default_timeout=None, + client_info=client_info, + ), + self.create_session_entity_type: gapic_v1.method.wrap_method( + self.create_session_entity_type, + default_timeout=None, + client_info=client_info, + ), + self.update_session_entity_type: gapic_v1.method.wrap_method( + self.update_session_entity_type, + default_timeout=None, + client_info=client_info, + ), + self.delete_session_entity_type: gapic_v1.method.wrap_method( + self.delete_session_entity_type, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_session_entity_types(self) -> Callable[ + [session_entity_type.ListSessionEntityTypesRequest], + Union[ + session_entity_type.ListSessionEntityTypesResponse, + Awaitable[session_entity_type.ListSessionEntityTypesResponse] + ]]: + raise NotImplementedError() + + @property + def get_session_entity_type(self) -> Callable[ + [session_entity_type.GetSessionEntityTypeRequest], + Union[ + session_entity_type.SessionEntityType, + Awaitable[session_entity_type.SessionEntityType] + ]]: + raise NotImplementedError() + + @property + def create_session_entity_type(self) -> Callable[ + [gcd_session_entity_type.CreateSessionEntityTypeRequest], + Union[ + gcd_session_entity_type.SessionEntityType, + Awaitable[gcd_session_entity_type.SessionEntityType] + ]]: + raise NotImplementedError() + + @property + def update_session_entity_type(self) -> Callable[ + [gcd_session_entity_type.UpdateSessionEntityTypeRequest], + Union[ + gcd_session_entity_type.SessionEntityType, + Awaitable[gcd_session_entity_type.SessionEntityType] + ]]: + raise NotImplementedError() + + @property + def delete_session_entity_type(self) -> Callable[ + [session_entity_type.DeleteSessionEntityTypeRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'SessionEntityTypesTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc.py new file mode 100644 index 000000000..501c21c57 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc.py @@ -0,0 +1,380 @@ +# -*- 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 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import session_entity_type +from google.cloud.dialogflow_v2beta1.types import session_entity_type as gcd_session_entity_type +from google.protobuf import empty_pb2 # type: ignore +from .base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO + + +class SessionEntityTypesGrpcTransport(SessionEntityTypesTransport): + """gRPC backend transport for SessionEntityTypes. + + Service for managing + [SessionEntityTypes][google.cloud.dialogflow.v2beta1.SessionEntityType]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 = 'dialogflow.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 list_session_entity_types(self) -> Callable[ + [session_entity_type.ListSessionEntityTypesRequest], + session_entity_type.ListSessionEntityTypesResponse]: + r"""Return a callable for the list session entity types method over gRPC. + + Returns the list of all session entity types in the + specified session. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Returns: + Callable[[~.ListSessionEntityTypesRequest], + ~.ListSessionEntityTypesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_session_entity_types' not in self._stubs: + self._stubs['list_session_entity_types'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.SessionEntityTypes/ListSessionEntityTypes', + request_serializer=session_entity_type.ListSessionEntityTypesRequest.serialize, + response_deserializer=session_entity_type.ListSessionEntityTypesResponse.deserialize, + ) + return self._stubs['list_session_entity_types'] + + @property + def get_session_entity_type(self) -> Callable[ + [session_entity_type.GetSessionEntityTypeRequest], + session_entity_type.SessionEntityType]: + r"""Return a callable for the get session entity type method over gRPC. + + Retrieves the specified session entity type. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Returns: + Callable[[~.GetSessionEntityTypeRequest], + ~.SessionEntityType]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_session_entity_type' not in self._stubs: + self._stubs['get_session_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.SessionEntityTypes/GetSessionEntityType', + request_serializer=session_entity_type.GetSessionEntityTypeRequest.serialize, + response_deserializer=session_entity_type.SessionEntityType.deserialize, + ) + return self._stubs['get_session_entity_type'] + + @property + def create_session_entity_type(self) -> Callable[ + [gcd_session_entity_type.CreateSessionEntityTypeRequest], + gcd_session_entity_type.SessionEntityType]: + r"""Return a callable for the create session entity type method over gRPC. + + Creates a session entity type. + If the specified session entity type already exists, + overrides the session entity type. + + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Returns: + Callable[[~.CreateSessionEntityTypeRequest], + ~.SessionEntityType]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_session_entity_type' not in self._stubs: + self._stubs['create_session_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.SessionEntityTypes/CreateSessionEntityType', + request_serializer=gcd_session_entity_type.CreateSessionEntityTypeRequest.serialize, + response_deserializer=gcd_session_entity_type.SessionEntityType.deserialize, + ) + return self._stubs['create_session_entity_type'] + + @property + def update_session_entity_type(self) -> Callable[ + [gcd_session_entity_type.UpdateSessionEntityTypeRequest], + gcd_session_entity_type.SessionEntityType]: + r"""Return a callable for the update session entity type method over gRPC. + + Updates the specified session entity type. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Returns: + Callable[[~.UpdateSessionEntityTypeRequest], + ~.SessionEntityType]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_session_entity_type' not in self._stubs: + self._stubs['update_session_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.SessionEntityTypes/UpdateSessionEntityType', + request_serializer=gcd_session_entity_type.UpdateSessionEntityTypeRequest.serialize, + response_deserializer=gcd_session_entity_type.SessionEntityType.deserialize, + ) + return self._stubs['update_session_entity_type'] + + @property + def delete_session_entity_type(self) -> Callable[ + [session_entity_type.DeleteSessionEntityTypeRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete session entity type method over gRPC. + + Deletes the specified session entity type. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Returns: + Callable[[~.DeleteSessionEntityTypeRequest], + ~.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_session_entity_type' not in self._stubs: + self._stubs['delete_session_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.SessionEntityTypes/DeleteSessionEntityType', + request_serializer=session_entity_type.DeleteSessionEntityTypeRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_session_entity_type'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'SessionEntityTypesGrpcTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc_asyncio.py new file mode 100644 index 000000000..1024b4307 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc_asyncio.py @@ -0,0 +1,384 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import session_entity_type +from google.cloud.dialogflow_v2beta1.types import session_entity_type as gcd_session_entity_type +from google.protobuf import empty_pb2 # type: ignore +from .base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO +from .grpc import SessionEntityTypesGrpcTransport + + +class SessionEntityTypesGrpcAsyncIOTransport(SessionEntityTypesTransport): + """gRPC AsyncIO backend transport for SessionEntityTypes. + + Service for managing + [SessionEntityTypes][google.cloud.dialogflow.v2beta1.SessionEntityType]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 list_session_entity_types(self) -> Callable[ + [session_entity_type.ListSessionEntityTypesRequest], + Awaitable[session_entity_type.ListSessionEntityTypesResponse]]: + r"""Return a callable for the list session entity types method over gRPC. + + Returns the list of all session entity types in the + specified session. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Returns: + Callable[[~.ListSessionEntityTypesRequest], + Awaitable[~.ListSessionEntityTypesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_session_entity_types' not in self._stubs: + self._stubs['list_session_entity_types'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.SessionEntityTypes/ListSessionEntityTypes', + request_serializer=session_entity_type.ListSessionEntityTypesRequest.serialize, + response_deserializer=session_entity_type.ListSessionEntityTypesResponse.deserialize, + ) + return self._stubs['list_session_entity_types'] + + @property + def get_session_entity_type(self) -> Callable[ + [session_entity_type.GetSessionEntityTypeRequest], + Awaitable[session_entity_type.SessionEntityType]]: + r"""Return a callable for the get session entity type method over gRPC. + + Retrieves the specified session entity type. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Returns: + Callable[[~.GetSessionEntityTypeRequest], + Awaitable[~.SessionEntityType]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_session_entity_type' not in self._stubs: + self._stubs['get_session_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.SessionEntityTypes/GetSessionEntityType', + request_serializer=session_entity_type.GetSessionEntityTypeRequest.serialize, + response_deserializer=session_entity_type.SessionEntityType.deserialize, + ) + return self._stubs['get_session_entity_type'] + + @property + def create_session_entity_type(self) -> Callable[ + [gcd_session_entity_type.CreateSessionEntityTypeRequest], + Awaitable[gcd_session_entity_type.SessionEntityType]]: + r"""Return a callable for the create session entity type method over gRPC. + + Creates a session entity type. + If the specified session entity type already exists, + overrides the session entity type. + + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Returns: + Callable[[~.CreateSessionEntityTypeRequest], + Awaitable[~.SessionEntityType]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_session_entity_type' not in self._stubs: + self._stubs['create_session_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.SessionEntityTypes/CreateSessionEntityType', + request_serializer=gcd_session_entity_type.CreateSessionEntityTypeRequest.serialize, + response_deserializer=gcd_session_entity_type.SessionEntityType.deserialize, + ) + return self._stubs['create_session_entity_type'] + + @property + def update_session_entity_type(self) -> Callable[ + [gcd_session_entity_type.UpdateSessionEntityTypeRequest], + Awaitable[gcd_session_entity_type.SessionEntityType]]: + r"""Return a callable for the update session entity type method over gRPC. + + Updates the specified session entity type. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Returns: + Callable[[~.UpdateSessionEntityTypeRequest], + Awaitable[~.SessionEntityType]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_session_entity_type' not in self._stubs: + self._stubs['update_session_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.SessionEntityTypes/UpdateSessionEntityType', + request_serializer=gcd_session_entity_type.UpdateSessionEntityTypeRequest.serialize, + response_deserializer=gcd_session_entity_type.SessionEntityType.deserialize, + ) + return self._stubs['update_session_entity_type'] + + @property + def delete_session_entity_type(self) -> Callable[ + [session_entity_type.DeleteSessionEntityTypeRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete session entity type method over gRPC. + + Deletes the specified session entity type. + This method doesn't work with Google Assistant + integration. Contact Dialogflow support if you need to + use session entities with Google Assistant integration. + + Returns: + Callable[[~.DeleteSessionEntityTypeRequest], + 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_session_entity_type' not in self._stubs: + self._stubs['delete_session_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.SessionEntityTypes/DeleteSessionEntityType', + request_serializer=session_entity_type.DeleteSessionEntityTypeRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_session_entity_type'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'SessionEntityTypesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/__init__.py new file mode 100644 index 000000000..92490cc5a --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/__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 SessionsClient +from .async_client import SessionsAsyncClient + +__all__ = ( + 'SessionsClient', + 'SessionsAsyncClient', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/async_client.py new file mode 100644 index 000000000..fa0f1b558 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/async_client.py @@ -0,0 +1,429 @@ +# -*- 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, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2beta1.types import audio_config +from google.cloud.dialogflow_v2beta1.types import session +from google.cloud.dialogflow_v2beta1.types import session as gcd_session +from google.rpc import status_pb2 # type: ignore +from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport +from .client import SessionsClient + + +class SessionsAsyncClient: + """A service used for session interactions. + + For more information, see the `API interactions + guide `__. + """ + + _client: SessionsClient + + DEFAULT_ENDPOINT = SessionsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SessionsClient.DEFAULT_MTLS_ENDPOINT + + context_path = staticmethod(SessionsClient.context_path) + parse_context_path = staticmethod(SessionsClient.parse_context_path) + document_path = staticmethod(SessionsClient.document_path) + parse_document_path = staticmethod(SessionsClient.parse_document_path) + intent_path = staticmethod(SessionsClient.intent_path) + parse_intent_path = staticmethod(SessionsClient.parse_intent_path) + session_path = staticmethod(SessionsClient.session_path) + parse_session_path = staticmethod(SessionsClient.parse_session_path) + session_entity_type_path = staticmethod(SessionsClient.session_entity_type_path) + parse_session_entity_type_path = staticmethod(SessionsClient.parse_session_entity_type_path) + common_billing_account_path = staticmethod(SessionsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SessionsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SessionsClient.common_folder_path) + parse_common_folder_path = staticmethod(SessionsClient.parse_common_folder_path) + common_organization_path = staticmethod(SessionsClient.common_organization_path) + parse_common_organization_path = staticmethod(SessionsClient.parse_common_organization_path) + common_project_path = staticmethod(SessionsClient.common_project_path) + parse_common_project_path = staticmethod(SessionsClient.parse_common_project_path) + common_location_path = staticmethod(SessionsClient.common_location_path) + parse_common_location_path = staticmethod(SessionsClient.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: + SessionsAsyncClient: The constructed client. + """ + return SessionsClient.from_service_account_info.__func__(SessionsAsyncClient, 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: + SessionsAsyncClient: The constructed client. + """ + return SessionsClient.from_service_account_file.__func__(SessionsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SessionsTransport: + """Returns the transport used by the client instance. + + Returns: + SessionsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SessionsClient).get_transport_class, type(SessionsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, SessionsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the sessions 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, ~.SessionsTransport]): 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 = SessionsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def detect_intent(self, + request: Union[gcd_session.DetectIntentRequest, dict] = None, + *, + session: str = None, + query_input: gcd_session.QueryInput = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_session.DetectIntentResponse: + r"""Processes a natural language query and returns structured, + actionable data as a result. This method is not idempotent, + because it may cause contexts and session entity types to be + updated, which in turn might affect results of future queries. + + If you might use `Agent + Assist `__ or + other CCAI products now or in the future, consider using + [AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent] + instead of ``DetectIntent``. ``AnalyzeContent`` has additional + functionality for Agent Assist and other CCAI products. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.DetectIntentRequest, dict]): + The request object. The request to detect user's intent. + session (:class:`str`): + Required. The name of the session this query is sent to. + Supported formats: + + - \`projects//agent/sessions/, + - ``projects//locations//agent/sessions/``, + - ``projects//agent/environments//users//sessions/``, + - ``projects//locations//agent/environments//users//sessions/``, + + If ``Location ID`` is not specified we assume default + 'us' location. If ``Environment ID`` is not specified, + we assume default 'draft' environment + (``Environment ID`` might be referred to as environment + name at some places). If ``User ID`` is not specified, + we are using "-". It's up to the API caller to choose an + appropriate ``Session ID`` and ``User Id``. They can be + a random number or some type of user and session + identifiers (preferably hashed). The length of the + ``Session ID`` and ``User ID`` must not exceed 36 + characters. For more information, see the `API + interactions + guide `__. + + Note: Always use agent versions for production traffic. + See `Versions and + environments `__. + + This corresponds to the ``session`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query_input (:class:`google.cloud.dialogflow_v2beta1.types.QueryInput`): + Required. The input specification. It + can be set to: + 1. an audio config + which instructs the speech + recognizer how to process the speech + audio, + 2. a conversational query in the form + of text, or + 3. an event that specifies which intent + to trigger. + + This corresponds to the ``query_input`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.DetectIntentResponse: + The message returned from the + DetectIntent method. + + """ + # 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([session, query_input]) + if request is 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 = gcd_session.DetectIntentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if session is not None: + request.session = session + if query_input is not None: + request.query_input = query_input + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.detect_intent, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=220.0, + ), + default_timeout=220.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(( + ("session", request.session), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def streaming_detect_intent(self, + requests: AsyncIterator[session.StreamingDetectIntentRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Awaitable[AsyncIterable[session.StreamingDetectIntentResponse]]: + r"""Processes a natural language query in audio format in a + streaming fashion and returns structured, actionable data as a + result. This method is only available via the gRPC API (not + REST). + + If you might use `Agent + Assist `__ or + other CCAI products now or in the future, consider using + [StreamingAnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.StreamingAnalyzeContent] + instead of ``StreamingDetectIntent``. + ``StreamingAnalyzeContent`` has additional functionality for + Agent Assist and other CCAI products. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Args: + requests (AsyncIterator[`google.cloud.dialogflow_v2beta1.types.StreamingDetectIntentRequest`]): + The request object AsyncIterator. The top-level message sent by the + client to the + [Sessions.StreamingDetectIntent][google.cloud.dialogflow.v2beta1.Sessions.StreamingDetectIntent] + method. + Multiple request messages should be sent in order: + + 1. The first message must contain + [session][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.session], + [query_input][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_input] + plus optionally + [query_params][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_params]. + If the client wants to receive an audio response, it + should also contain + [output_audio_config][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.output_audio_config]. + The message must not contain + [input_audio][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.input_audio]. + 2. If + [query_input][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_input] + was set to + [query_input.audio_config][google.cloud.dialogflow.v2beta1.InputAudioConfig], + all subsequent messages must contain + [input_audio][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.input_audio] + to continue with Speech recognition. + If you decide to rather detect an intent from text + input after you already started Speech recognition, + please send a message with + [query_input.text][google.cloud.dialogflow.v2beta1.QueryInput.text]. + However, note that: + + * Dialogflow will bill you for the audio duration so + far. * Dialogflow discards all Speech recognition + results in favor of the input text. + * Dialogflow will use the language code from the + first message. + After you sent all input, you must half-close or abort + the request stream. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + AsyncIterable[google.cloud.dialogflow_v2beta1.types.StreamingDetectIntentResponse]: + The top-level message returned from the + StreamingDetectIntent method. + + Multiple response messages can be returned in order: + + 1. If the StreamingDetectIntentRequest.input_audio + field was set, the recognition_result field is + populated for one or more messages. See the + [StreamingRecognitionResult][google.cloud.dialogflow.v2beta1.StreamingRecognitionResult] + message for details about the result message + sequence. + 2. The next message contains response_id, + query_result, alternative_query_results and + optionally webhook_status if a WebHook was called. + 3. If output_audio_config was specified in the + request or agent-level speech synthesizer is + configured, all subsequent messages contain + output_audio and output_audio_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.streaming_detect_intent, + default_timeout=220.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SessionsAsyncClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/client.py new file mode 100644 index 000000000..6eebfe35a --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/client.py @@ -0,0 +1,653 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2beta1.types import audio_config +from google.cloud.dialogflow_v2beta1.types import session +from google.cloud.dialogflow_v2beta1.types import session as gcd_session +from google.rpc import status_pb2 # type: ignore +from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SessionsGrpcTransport +from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport + + +class SessionsClientMeta(type): + """Metaclass for the Sessions 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[SessionsTransport]] + _transport_registry["grpc"] = SessionsGrpcTransport + _transport_registry["grpc_asyncio"] = SessionsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[SessionsTransport]: + """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 SessionsClient(metaclass=SessionsClientMeta): + """A service used for session interactions. + + For more information, see the `API interactions + guide `__. + """ + + @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 = "dialogflow.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: + SessionsClient: 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: + SessionsClient: 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) -> SessionsTransport: + """Returns the transport used by the client instance. + + Returns: + SessionsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def context_path(project: str,session: str,context: str,) -> str: + """Returns a fully-qualified context string.""" + return "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) + + @staticmethod + def parse_context_path(path: str) -> Dict[str,str]: + """Parses a context path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/contexts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def document_path(project: str,knowledge_base: str,document: str,) -> str: + """Returns a fully-qualified document string.""" + return "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format(project=project, knowledge_base=knowledge_base, document=document, ) + + @staticmethod + def parse_document_path(path: str) -> Dict[str,str]: + """Parses a document path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/knowledgeBases/(?P.+?)/documents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def intent_path(project: str,intent: str,) -> str: + """Returns a fully-qualified intent string.""" + return "projects/{project}/agent/intents/{intent}".format(project=project, intent=intent, ) + + @staticmethod + def parse_intent_path(path: str) -> Dict[str,str]: + """Parses a intent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/intents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def session_path(project: str,session: str,) -> str: + """Returns a fully-qualified session string.""" + return "projects/{project}/agent/sessions/{session}".format(project=project, session=session, ) + + @staticmethod + def parse_session_path(path: str) -> Dict[str,str]: + """Parses a session path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def session_entity_type_path(project: str,session: str,entity_type: str,) -> str: + """Returns a fully-qualified session_entity_type string.""" + return "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format(project=project, session=session, entity_type=entity_type, ) + + @staticmethod + def parse_session_entity_type_path(path: str) -> Dict[str,str]: + """Parses a session_entity_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/entityTypes/(?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, SessionsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the sessions 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, SessionsTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, SessionsTransport): + # transport is a SessionsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def detect_intent(self, + request: Union[gcd_session.DetectIntentRequest, dict] = None, + *, + session: str = None, + query_input: gcd_session.QueryInput = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_session.DetectIntentResponse: + r"""Processes a natural language query and returns structured, + actionable data as a result. This method is not idempotent, + because it may cause contexts and session entity types to be + updated, which in turn might affect results of future queries. + + If you might use `Agent + Assist `__ or + other CCAI products now or in the future, consider using + [AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent] + instead of ``DetectIntent``. ``AnalyzeContent`` has additional + functionality for Agent Assist and other CCAI products. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.DetectIntentRequest, dict]): + The request object. The request to detect user's intent. + session (str): + Required. The name of the session this query is sent to. + Supported formats: + + - \`projects//agent/sessions/, + - ``projects//locations//agent/sessions/``, + - ``projects//agent/environments//users//sessions/``, + - ``projects//locations//agent/environments//users//sessions/``, + + If ``Location ID`` is not specified we assume default + 'us' location. If ``Environment ID`` is not specified, + we assume default 'draft' environment + (``Environment ID`` might be referred to as environment + name at some places). If ``User ID`` is not specified, + we are using "-". It's up to the API caller to choose an + appropriate ``Session ID`` and ``User Id``. They can be + a random number or some type of user and session + identifiers (preferably hashed). The length of the + ``Session ID`` and ``User ID`` must not exceed 36 + characters. For more information, see the `API + interactions + guide `__. + + Note: Always use agent versions for production traffic. + See `Versions and + environments `__. + + This corresponds to the ``session`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query_input (google.cloud.dialogflow_v2beta1.types.QueryInput): + Required. The input specification. It + can be set to: + 1. an audio config + which instructs the speech + recognizer how to process the speech + audio, + 2. a conversational query in the form + of text, or + 3. an event that specifies which intent + to trigger. + + This corresponds to the ``query_input`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.DetectIntentResponse: + The message returned from the + DetectIntent method. + + """ + # 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([session, query_input]) + if request is 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 gcd_session.DetectIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_session.DetectIntentRequest): + request = gcd_session.DetectIntentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if session is not None: + request.session = session + if query_input is not None: + request.query_input = query_input + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.detect_intent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("session", request.session), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def streaming_detect_intent(self, + requests: Iterator[session.StreamingDetectIntentRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Iterable[session.StreamingDetectIntentResponse]: + r"""Processes a natural language query in audio format in a + streaming fashion and returns structured, actionable data as a + result. This method is only available via the gRPC API (not + REST). + + If you might use `Agent + Assist `__ or + other CCAI products now or in the future, consider using + [StreamingAnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.StreamingAnalyzeContent] + instead of ``StreamingDetectIntent``. + ``StreamingAnalyzeContent`` has additional functionality for + Agent Assist and other CCAI products. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Args: + requests (Iterator[google.cloud.dialogflow_v2beta1.types.StreamingDetectIntentRequest]): + The request object iterator. The top-level message sent by the + client to the + [Sessions.StreamingDetectIntent][google.cloud.dialogflow.v2beta1.Sessions.StreamingDetectIntent] + method. + Multiple request messages should be sent in order: + + 1. The first message must contain + [session][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.session], + [query_input][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_input] + plus optionally + [query_params][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_params]. + If the client wants to receive an audio response, it + should also contain + [output_audio_config][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.output_audio_config]. + The message must not contain + [input_audio][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.input_audio]. + 2. If + [query_input][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_input] + was set to + [query_input.audio_config][google.cloud.dialogflow.v2beta1.InputAudioConfig], + all subsequent messages must contain + [input_audio][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.input_audio] + to continue with Speech recognition. + If you decide to rather detect an intent from text + input after you already started Speech recognition, + please send a message with + [query_input.text][google.cloud.dialogflow.v2beta1.QueryInput.text]. + However, note that: + + * Dialogflow will bill you for the audio duration so + far. * Dialogflow discards all Speech recognition + results in favor of the input text. + * Dialogflow will use the language code from the + first message. + After you sent all input, you must half-close or abort + the request stream. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + Iterable[google.cloud.dialogflow_v2beta1.types.StreamingDetectIntentResponse]: + The top-level message returned from the + StreamingDetectIntent method. + + Multiple response messages can be returned in order: + + 1. If the StreamingDetectIntentRequest.input_audio + field was set, the recognition_result field is + populated for one or more messages. See the + [StreamingRecognitionResult][google.cloud.dialogflow.v2beta1.StreamingRecognitionResult] + message for details about the result message + sequence. + 2. The next message contains response_id, + query_result, alternative_query_results and + optionally webhook_status if a WebHook was called. + 3. If output_audio_config was specified in the + request or agent-level speech synthesizer is + configured, all subsequent messages contain + output_audio and output_audio_config. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.streaming_detect_intent] + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SessionsClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/__init__.py new file mode 100644 index 000000000..fde19f616 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/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 SessionsTransport +from .grpc import SessionsGrpcTransport +from .grpc_asyncio import SessionsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SessionsTransport]] +_transport_registry['grpc'] = SessionsGrpcTransport +_transport_registry['grpc_asyncio'] = SessionsGrpcAsyncIOTransport + +__all__ = ( + 'SessionsTransport', + 'SessionsGrpcTransport', + 'SessionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/base.py new file mode 100644 index 000000000..1ec4b0db7 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/base.py @@ -0,0 +1,168 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.types import session +from google.cloud.dialogflow_v2beta1.types import session as gcd_session + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class SessionsTransport(abc.ABC): + """Abstract transport class for Sessions.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.detect_intent: gapic_v1.method.wrap_method( + self.detect_intent, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=220.0, + ), + default_timeout=220.0, + client_info=client_info, + ), + self.streaming_detect_intent: gapic_v1.method.wrap_method( + self.streaming_detect_intent, + default_timeout=220.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def detect_intent(self) -> Callable[ + [gcd_session.DetectIntentRequest], + Union[ + gcd_session.DetectIntentResponse, + Awaitable[gcd_session.DetectIntentResponse] + ]]: + raise NotImplementedError() + + @property + def streaming_detect_intent(self) -> Callable[ + [session.StreamingDetectIntentRequest], + Union[ + session.StreamingDetectIntentResponse, + Awaitable[session.StreamingDetectIntentResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'SessionsTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc.py new file mode 100644 index 000000000..4510a25df --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc.py @@ -0,0 +1,313 @@ +# -*- 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 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import session +from google.cloud.dialogflow_v2beta1.types import session as gcd_session +from .base import SessionsTransport, DEFAULT_CLIENT_INFO + + +class SessionsGrpcTransport(SessionsTransport): + """gRPC backend transport for Sessions. + + A service used for session interactions. + + For more information, see the `API interactions + guide `__. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 = 'dialogflow.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 detect_intent(self) -> Callable[ + [gcd_session.DetectIntentRequest], + gcd_session.DetectIntentResponse]: + r"""Return a callable for the detect intent method over gRPC. + + Processes a natural language query and returns structured, + actionable data as a result. This method is not idempotent, + because it may cause contexts and session entity types to be + updated, which in turn might affect results of future queries. + + If you might use `Agent + Assist `__ or + other CCAI products now or in the future, consider using + [AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent] + instead of ``DetectIntent``. ``AnalyzeContent`` has additional + functionality for Agent Assist and other CCAI products. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Returns: + Callable[[~.DetectIntentRequest], + ~.DetectIntentResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'detect_intent' not in self._stubs: + self._stubs['detect_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Sessions/DetectIntent', + request_serializer=gcd_session.DetectIntentRequest.serialize, + response_deserializer=gcd_session.DetectIntentResponse.deserialize, + ) + return self._stubs['detect_intent'] + + @property + def streaming_detect_intent(self) -> Callable[ + [session.StreamingDetectIntentRequest], + session.StreamingDetectIntentResponse]: + r"""Return a callable for the streaming detect intent method over gRPC. + + Processes a natural language query in audio format in a + streaming fashion and returns structured, actionable data as a + result. This method is only available via the gRPC API (not + REST). + + If you might use `Agent + Assist `__ or + other CCAI products now or in the future, consider using + [StreamingAnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.StreamingAnalyzeContent] + instead of ``StreamingDetectIntent``. + ``StreamingAnalyzeContent`` has additional functionality for + Agent Assist and other CCAI products. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Returns: + Callable[[~.StreamingDetectIntentRequest], + ~.StreamingDetectIntentResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'streaming_detect_intent' not in self._stubs: + self._stubs['streaming_detect_intent'] = self.grpc_channel.stream_stream( + '/google.cloud.dialogflow.v2beta1.Sessions/StreamingDetectIntent', + request_serializer=session.StreamingDetectIntentRequest.serialize, + response_deserializer=session.StreamingDetectIntentResponse.deserialize, + ) + return self._stubs['streaming_detect_intent'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'SessionsGrpcTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc_asyncio.py new file mode 100644 index 000000000..c8785a4e4 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc_asyncio.py @@ -0,0 +1,317 @@ +# -*- 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 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import session +from google.cloud.dialogflow_v2beta1.types import session as gcd_session +from .base import SessionsTransport, DEFAULT_CLIENT_INFO +from .grpc import SessionsGrpcTransport + + +class SessionsGrpcAsyncIOTransport(SessionsTransport): + """gRPC AsyncIO backend transport for Sessions. + + A service used for session interactions. + + For more information, see the `API interactions + guide `__. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 detect_intent(self) -> Callable[ + [gcd_session.DetectIntentRequest], + Awaitable[gcd_session.DetectIntentResponse]]: + r"""Return a callable for the detect intent method over gRPC. + + Processes a natural language query and returns structured, + actionable data as a result. This method is not idempotent, + because it may cause contexts and session entity types to be + updated, which in turn might affect results of future queries. + + If you might use `Agent + Assist `__ or + other CCAI products now or in the future, consider using + [AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent] + instead of ``DetectIntent``. ``AnalyzeContent`` has additional + functionality for Agent Assist and other CCAI products. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Returns: + Callable[[~.DetectIntentRequest], + Awaitable[~.DetectIntentResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'detect_intent' not in self._stubs: + self._stubs['detect_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Sessions/DetectIntent', + request_serializer=gcd_session.DetectIntentRequest.serialize, + response_deserializer=gcd_session.DetectIntentResponse.deserialize, + ) + return self._stubs['detect_intent'] + + @property + def streaming_detect_intent(self) -> Callable[ + [session.StreamingDetectIntentRequest], + Awaitable[session.StreamingDetectIntentResponse]]: + r"""Return a callable for the streaming detect intent method over gRPC. + + Processes a natural language query in audio format in a + streaming fashion and returns structured, actionable data as a + result. This method is only available via the gRPC API (not + REST). + + If you might use `Agent + Assist `__ or + other CCAI products now or in the future, consider using + [StreamingAnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.StreamingAnalyzeContent] + instead of ``StreamingDetectIntent``. + ``StreamingAnalyzeContent`` has additional functionality for + Agent Assist and other CCAI products. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Returns: + Callable[[~.StreamingDetectIntentRequest], + Awaitable[~.StreamingDetectIntentResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'streaming_detect_intent' not in self._stubs: + self._stubs['streaming_detect_intent'] = self.grpc_channel.stream_stream( + '/google.cloud.dialogflow.v2beta1.Sessions/StreamingDetectIntent', + request_serializer=session.StreamingDetectIntentRequest.serialize, + response_deserializer=session.StreamingDetectIntentResponse.deserialize, + ) + return self._stubs['streaming_detect_intent'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'SessionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/__init__.py new file mode 100644 index 000000000..630246bde --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/__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 VersionsClient +from .async_client import VersionsAsyncClient + +__all__ = ( + 'VersionsClient', + 'VersionsAsyncClient', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/async_client.py new file mode 100644 index 000000000..be49aaef2 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/async_client.py @@ -0,0 +1,648 @@ +# -*- 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 + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2beta1.services.versions import pagers +from google.cloud.dialogflow_v2beta1.types import version +from google.cloud.dialogflow_v2beta1.types import version as gcd_version +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport +from .client import VersionsClient + + +class VersionsAsyncClient: + """Service for managing + [Versions][google.cloud.dialogflow.v2beta1.Version]. + """ + + _client: VersionsClient + + DEFAULT_ENDPOINT = VersionsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = VersionsClient.DEFAULT_MTLS_ENDPOINT + + version_path = staticmethod(VersionsClient.version_path) + parse_version_path = staticmethod(VersionsClient.parse_version_path) + common_billing_account_path = staticmethod(VersionsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(VersionsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(VersionsClient.common_folder_path) + parse_common_folder_path = staticmethod(VersionsClient.parse_common_folder_path) + common_organization_path = staticmethod(VersionsClient.common_organization_path) + parse_common_organization_path = staticmethod(VersionsClient.parse_common_organization_path) + common_project_path = staticmethod(VersionsClient.common_project_path) + parse_common_project_path = staticmethod(VersionsClient.parse_common_project_path) + common_location_path = staticmethod(VersionsClient.common_location_path) + parse_common_location_path = staticmethod(VersionsClient.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: + VersionsAsyncClient: The constructed client. + """ + return VersionsClient.from_service_account_info.__func__(VersionsAsyncClient, 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: + VersionsAsyncClient: The constructed client. + """ + return VersionsClient.from_service_account_file.__func__(VersionsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> VersionsTransport: + """Returns the transport used by the client instance. + + Returns: + VersionsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(VersionsClient).get_transport_class, type(VersionsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, VersionsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the versions 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, ~.VersionsTransport]): 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 = VersionsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_versions(self, + request: Union[version.ListVersionsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVersionsAsyncPager: + r"""Returns the list of all versions of the specified + agent. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListVersionsRequest, dict]): + The request object. The request message for + [Versions.ListVersions][google.cloud.dialogflow.v2beta1.Versions.ListVersions]. + parent (:class:`str`): + Required. The agent to list all versions from. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + 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.dialogflow_v2beta1.services.versions.pagers.ListVersionsAsyncPager: + The response message for + [Versions.ListVersions][google.cloud.dialogflow.v2beta1.Versions.ListVersions]. + + 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 = version.ListVersionsRequest(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_versions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListVersionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_version(self, + request: Union[version.GetVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> version.Version: + r"""Retrieves the specified agent version. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetVersionRequest, dict]): + The request object. The request message for + [Versions.GetVersion][google.cloud.dialogflow.v2beta1.Versions.GetVersion]. + name (:class:`str`): + Required. The name of the version. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + 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.dialogflow_v2beta1.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # 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 = version.GetVersionRequest(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_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_version(self, + request: Union[gcd_version.CreateVersionRequest, dict] = None, + *, + parent: str = None, + version: gcd_version.Version = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: + r"""Creates an agent version. + The new version points to the agent instance in the + "default" environment. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.CreateVersionRequest, dict]): + The request object. The request message for + [Versions.CreateVersion][google.cloud.dialogflow.v2beta1.Versions.CreateVersion]. + parent (:class:`str`): + Required. The agent to create a version for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + version (:class:`google.cloud.dialogflow_v2beta1.types.Version`): + Required. The version to create. + This corresponds to the ``version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # 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, version]) + if request is 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 = gcd_version.CreateVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if version is not None: + request.version = version + + # 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_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_version(self, + request: Union[gcd_version.UpdateVersionRequest, dict] = None, + *, + version: gcd_version.Version = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: + r"""Updates the specified agent version. + Note that this method does not allow you to update the + state of the agent the given version points to. It + allows you to update only mutable properties of the + version resource. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.UpdateVersionRequest, dict]): + The request object. The request message for + [Versions.UpdateVersion][google.cloud.dialogflow.v2beta1.Versions.UpdateVersion]. + version (:class:`google.cloud.dialogflow_v2beta1.types.Version`): + Required. The version to update. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + This corresponds to the ``version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # 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([version, 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 = gcd_version.UpdateVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if version is not None: + request.version = version + 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_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("version.name", request.version.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_version(self, + request: Union[version.DeleteVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Delete the specified agent version. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.DeleteVersionRequest, dict]): + The request object. The request message for + [Versions.DeleteVersion][google.cloud.dialogflow.v2beta1.Versions.DeleteVersion]. + name (:class:`str`): + Required. The name of the version to delete. Supported + formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + 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 = version.DeleteVersionRequest(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_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "VersionsAsyncClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/client.py new file mode 100644 index 000000000..05767b14f --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/client.py @@ -0,0 +1,846 @@ +# -*- 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 os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.dialogflow_v2beta1.services.versions import pagers +from google.cloud.dialogflow_v2beta1.types import version +from google.cloud.dialogflow_v2beta1.types import version as gcd_version +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import VersionsGrpcTransport +from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport + + +class VersionsClientMeta(type): + """Metaclass for the Versions 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[VersionsTransport]] + _transport_registry["grpc"] = VersionsGrpcTransport + _transport_registry["grpc_asyncio"] = VersionsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[VersionsTransport]: + """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 VersionsClient(metaclass=VersionsClientMeta): + """Service for managing + [Versions][google.cloud.dialogflow.v2beta1.Version]. + """ + + @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 = "dialogflow.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: + VersionsClient: 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: + VersionsClient: 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) -> VersionsTransport: + """Returns the transport used by the client instance. + + Returns: + VersionsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def version_path(project: str,version: str,) -> str: + """Returns a fully-qualified version string.""" + return "projects/{project}/agent/versions/{version}".format(project=project, version=version, ) + + @staticmethod + def parse_version_path(path: str) -> Dict[str,str]: + """Parses a version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/versions/(?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, VersionsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the versions 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, VersionsTransport]): 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. + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + + 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, VersionsTransport): + # transport is a VersionsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_versions(self, + request: Union[version.ListVersionsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVersionsPager: + r"""Returns the list of all versions of the specified + agent. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.ListVersionsRequest, dict]): + The request object. The request message for + [Versions.ListVersions][google.cloud.dialogflow.v2beta1.Versions.ListVersions]. + parent (str): + Required. The agent to list all versions from. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + 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.dialogflow_v2beta1.services.versions.pagers.ListVersionsPager: + The response message for + [Versions.ListVersions][google.cloud.dialogflow.v2beta1.Versions.ListVersions]. + + 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 version.ListVersionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, version.ListVersionsRequest): + request = version.ListVersionsRequest(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_versions] + + # Certain 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.ListVersionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_version(self, + request: Union[version.GetVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> version.Version: + r"""Retrieves the specified agent version. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.GetVersionRequest, dict]): + The request object. The request message for + [Versions.GetVersion][google.cloud.dialogflow.v2beta1.Versions.GetVersion]. + name (str): + Required. The name of the version. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + 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.dialogflow_v2beta1.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # 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 version.GetVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, version.GetVersionRequest): + request = version.GetVersionRequest(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_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_version(self, + request: Union[gcd_version.CreateVersionRequest, dict] = None, + *, + parent: str = None, + version: gcd_version.Version = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: + r"""Creates an agent version. + The new version points to the agent instance in the + "default" environment. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.CreateVersionRequest, dict]): + The request object. The request message for + [Versions.CreateVersion][google.cloud.dialogflow.v2beta1.Versions.CreateVersion]. + parent (str): + Required. The agent to create a version for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + version (google.cloud.dialogflow_v2beta1.types.Version): + Required. The version to create. + This corresponds to the ``version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # 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, version]) + if request is 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 gcd_version.CreateVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_version.CreateVersionRequest): + request = gcd_version.CreateVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if version is not None: + request.version = version + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_version(self, + request: Union[gcd_version.UpdateVersionRequest, dict] = None, + *, + version: gcd_version.Version = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: + r"""Updates the specified agent version. + Note that this method does not allow you to update the + state of the agent the given version points to. It + allows you to update only mutable properties of the + version resource. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.UpdateVersionRequest, dict]): + The request object. The request message for + [Versions.UpdateVersion][google.cloud.dialogflow.v2beta1.Versions.UpdateVersion]. + version (google.cloud.dialogflow_v2beta1.types.Version): + Required. The version to update. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + This corresponds to the ``version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # 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([version, 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 gcd_version.UpdateVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_version.UpdateVersionRequest): + request = gcd_version.UpdateVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if version is not None: + request.version = version + 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_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("version.name", request.version.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_version(self, + request: Union[version.DeleteVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Delete the specified agent version. + + Args: + request (Union[google.cloud.dialogflow_v2beta1.types.DeleteVersionRequest, dict]): + The request object. The request message for + [Versions.DeleteVersion][google.cloud.dialogflow.v2beta1.Versions.DeleteVersion]. + name (str): + Required. The name of the version to delete. Supported + formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + 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 version.DeleteVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, version.DeleteVersionRequest): + request = version.DeleteVersionRequest(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_version] + + # Certain 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 __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "VersionsClient", +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/pagers.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/pagers.py new file mode 100644 index 000000000..9cdebf0d1 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/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, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflow_v2beta1.types import version + + +class ListVersionsPager: + """A pager for iterating through ``list_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListVersionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``versions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListVersions`` requests and continue to iterate + through the ``versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListVersionsResponse` + 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[..., version.ListVersionsResponse], + request: version.ListVersionsRequest, + response: version.ListVersionsResponse, + *, + 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.dialogflow_v2beta1.types.ListVersionsRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListVersionsResponse): + 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 = version.ListVersionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[version.ListVersionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[version.Version]: + for page in self.pages: + yield from page.versions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListVersionsAsyncPager: + """A pager for iterating through ``list_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListVersionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``versions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListVersions`` requests and continue to iterate + through the ``versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListVersionsResponse` + 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[version.ListVersionsResponse]], + request: version.ListVersionsRequest, + response: version.ListVersionsResponse, + *, + 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.dialogflow_v2beta1.types.ListVersionsRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListVersionsResponse): + 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 = version.ListVersionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[version.ListVersionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[version.Version]: + async def async_generator(): + async for page in self.pages: + for response in page.versions: + 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/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/__init__.py new file mode 100644 index 000000000..dfb70ce95 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/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 VersionsTransport +from .grpc import VersionsGrpcTransport +from .grpc_asyncio import VersionsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[VersionsTransport]] +_transport_registry['grpc'] = VersionsGrpcTransport +_transport_registry['grpc_asyncio'] = VersionsGrpcAsyncIOTransport + +__all__ = ( + 'VersionsTransport', + 'VersionsGrpcTransport', + 'VersionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/base.py new file mode 100644 index 000000000..e9c7a3d4d --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/base.py @@ -0,0 +1,205 @@ +# -*- 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 pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.types import version +from google.cloud.dialogflow_v2beta1.types import version as gcd_version +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-dialogflow', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class VersionsTransport(abc.ABC): + """Abstract transport class for Versions.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.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 = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_versions: gapic_v1.method.wrap_method( + self.list_versions, + default_timeout=None, + client_info=client_info, + ), + self.get_version: gapic_v1.method.wrap_method( + self.get_version, + default_timeout=None, + client_info=client_info, + ), + self.create_version: gapic_v1.method.wrap_method( + self.create_version, + default_timeout=None, + client_info=client_info, + ), + self.update_version: gapic_v1.method.wrap_method( + self.update_version, + default_timeout=None, + client_info=client_info, + ), + self.delete_version: gapic_v1.method.wrap_method( + self.delete_version, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_versions(self) -> Callable[ + [version.ListVersionsRequest], + Union[ + version.ListVersionsResponse, + Awaitable[version.ListVersionsResponse] + ]]: + raise NotImplementedError() + + @property + def get_version(self) -> Callable[ + [version.GetVersionRequest], + Union[ + version.Version, + Awaitable[version.Version] + ]]: + raise NotImplementedError() + + @property + def create_version(self) -> Callable[ + [gcd_version.CreateVersionRequest], + Union[ + gcd_version.Version, + Awaitable[gcd_version.Version] + ]]: + raise NotImplementedError() + + @property + def update_version(self) -> Callable[ + [gcd_version.UpdateVersionRequest], + Union[ + gcd_version.Version, + Awaitable[gcd_version.Version] + ]]: + raise NotImplementedError() + + @property + def delete_version(self) -> Callable[ + [version.DeleteVersionRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'VersionsTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc.py new file mode 100644 index 000000000..f31730666 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc.py @@ -0,0 +1,368 @@ +# -*- 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 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import version +from google.cloud.dialogflow_v2beta1.types import version as gcd_version +from google.protobuf import empty_pb2 # type: ignore +from .base import VersionsTransport, DEFAULT_CLIENT_INFO + + +class VersionsGrpcTransport(VersionsTransport): + """gRPC backend transport for Versions. + + Service for managing + [Versions][google.cloud.dialogflow.v2beta1.Version]. + + 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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 = 'dialogflow.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 list_versions(self) -> Callable[ + [version.ListVersionsRequest], + version.ListVersionsResponse]: + r"""Return a callable for the list versions method over gRPC. + + Returns the list of all versions of the specified + agent. + + Returns: + Callable[[~.ListVersionsRequest], + ~.ListVersionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_versions' not in self._stubs: + self._stubs['list_versions'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Versions/ListVersions', + request_serializer=version.ListVersionsRequest.serialize, + response_deserializer=version.ListVersionsResponse.deserialize, + ) + return self._stubs['list_versions'] + + @property + def get_version(self) -> Callable[ + [version.GetVersionRequest], + version.Version]: + r"""Return a callable for the get version method over gRPC. + + Retrieves the specified agent version. + + Returns: + Callable[[~.GetVersionRequest], + ~.Version]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_version' not in self._stubs: + self._stubs['get_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Versions/GetVersion', + request_serializer=version.GetVersionRequest.serialize, + response_deserializer=version.Version.deserialize, + ) + return self._stubs['get_version'] + + @property + def create_version(self) -> Callable[ + [gcd_version.CreateVersionRequest], + gcd_version.Version]: + r"""Return a callable for the create version method over gRPC. + + Creates an agent version. + The new version points to the agent instance in the + "default" environment. + + Returns: + Callable[[~.CreateVersionRequest], + ~.Version]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_version' not in self._stubs: + self._stubs['create_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Versions/CreateVersion', + request_serializer=gcd_version.CreateVersionRequest.serialize, + response_deserializer=gcd_version.Version.deserialize, + ) + return self._stubs['create_version'] + + @property + def update_version(self) -> Callable[ + [gcd_version.UpdateVersionRequest], + gcd_version.Version]: + r"""Return a callable for the update version method over gRPC. + + Updates the specified agent version. + Note that this method does not allow you to update the + state of the agent the given version points to. It + allows you to update only mutable properties of the + version resource. + + Returns: + Callable[[~.UpdateVersionRequest], + ~.Version]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_version' not in self._stubs: + self._stubs['update_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Versions/UpdateVersion', + request_serializer=gcd_version.UpdateVersionRequest.serialize, + response_deserializer=gcd_version.Version.deserialize, + ) + return self._stubs['update_version'] + + @property + def delete_version(self) -> Callable[ + [version.DeleteVersionRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete version method over gRPC. + + Delete the specified agent version. + + Returns: + Callable[[~.DeleteVersionRequest], + ~.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_version' not in self._stubs: + self._stubs['delete_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Versions/DeleteVersion', + request_serializer=version.DeleteVersionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_version'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'VersionsGrpcTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc_asyncio.py new file mode 100644 index 000000000..b83741d45 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc_asyncio.py @@ -0,0 +1,372 @@ +# -*- 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 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import version +from google.cloud.dialogflow_v2beta1.types import version as gcd_version +from google.protobuf import empty_pb2 # type: ignore +from .base import VersionsTransport, DEFAULT_CLIENT_INFO +from .grpc import VersionsGrpcTransport + + +class VersionsGrpcAsyncIOTransport(VersionsTransport): + """gRPC AsyncIO backend transport for Versions. + + Service for managing + [Versions][google.cloud.dialogflow.v2beta1.Version]. + + 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 = 'dialogflow.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 = 'dialogflow.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 application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + 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 list_versions(self) -> Callable[ + [version.ListVersionsRequest], + Awaitable[version.ListVersionsResponse]]: + r"""Return a callable for the list versions method over gRPC. + + Returns the list of all versions of the specified + agent. + + Returns: + Callable[[~.ListVersionsRequest], + Awaitable[~.ListVersionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_versions' not in self._stubs: + self._stubs['list_versions'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Versions/ListVersions', + request_serializer=version.ListVersionsRequest.serialize, + response_deserializer=version.ListVersionsResponse.deserialize, + ) + return self._stubs['list_versions'] + + @property + def get_version(self) -> Callable[ + [version.GetVersionRequest], + Awaitable[version.Version]]: + r"""Return a callable for the get version method over gRPC. + + Retrieves the specified agent version. + + Returns: + Callable[[~.GetVersionRequest], + Awaitable[~.Version]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_version' not in self._stubs: + self._stubs['get_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Versions/GetVersion', + request_serializer=version.GetVersionRequest.serialize, + response_deserializer=version.Version.deserialize, + ) + return self._stubs['get_version'] + + @property + def create_version(self) -> Callable[ + [gcd_version.CreateVersionRequest], + Awaitable[gcd_version.Version]]: + r"""Return a callable for the create version method over gRPC. + + Creates an agent version. + The new version points to the agent instance in the + "default" environment. + + Returns: + Callable[[~.CreateVersionRequest], + Awaitable[~.Version]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_version' not in self._stubs: + self._stubs['create_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Versions/CreateVersion', + request_serializer=gcd_version.CreateVersionRequest.serialize, + response_deserializer=gcd_version.Version.deserialize, + ) + return self._stubs['create_version'] + + @property + def update_version(self) -> Callable[ + [gcd_version.UpdateVersionRequest], + Awaitable[gcd_version.Version]]: + r"""Return a callable for the update version method over gRPC. + + Updates the specified agent version. + Note that this method does not allow you to update the + state of the agent the given version points to. It + allows you to update only mutable properties of the + version resource. + + Returns: + Callable[[~.UpdateVersionRequest], + Awaitable[~.Version]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_version' not in self._stubs: + self._stubs['update_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Versions/UpdateVersion', + request_serializer=gcd_version.UpdateVersionRequest.serialize, + response_deserializer=gcd_version.Version.deserialize, + ) + return self._stubs['update_version'] + + @property + def delete_version(self) -> Callable[ + [version.DeleteVersionRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete version method over gRPC. + + Delete the specified agent version. + + Returns: + Callable[[~.DeleteVersionRequest], + 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_version' not in self._stubs: + self._stubs['delete_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.v2beta1.Versions/DeleteVersion', + request_serializer=version.DeleteVersionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_version'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'VersionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/__init__.py new file mode 100644 index 000000000..e4730e2e8 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/__init__.py @@ -0,0 +1,446 @@ +# -*- 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 .agent import ( + Agent, + DeleteAgentRequest, + ExportAgentRequest, + ExportAgentResponse, + GetAgentRequest, + GetValidationResultRequest, + ImportAgentRequest, + RestoreAgentRequest, + SearchAgentsRequest, + SearchAgentsResponse, + SetAgentRequest, + SubAgent, + TrainAgentRequest, +) +from .answer_record import ( + AgentAssistantFeedback, + AgentAssistantRecord, + AnswerFeedback, + AnswerRecord, + GetAnswerRecordRequest, + ListAnswerRecordsRequest, + ListAnswerRecordsResponse, + UpdateAnswerRecordRequest, +) +from .audio_config import ( + InputAudioConfig, + OutputAudioConfig, + SpeechContext, + SpeechToTextConfig, + SpeechWordInfo, + SynthesizeSpeechConfig, + TelephonyDtmfEvents, + VoiceSelectionParams, + AudioEncoding, + OutputAudioEncoding, + SpeechModelVariant, + SsmlVoiceGender, + TelephonyDtmf, +) +from .context import ( + Context, + CreateContextRequest, + DeleteAllContextsRequest, + DeleteContextRequest, + GetContextRequest, + ListContextsRequest, + ListContextsResponse, + UpdateContextRequest, +) +from .conversation import ( + BatchCreateMessagesRequest, + BatchCreateMessagesResponse, + CompleteConversationRequest, + Conversation, + ConversationPhoneNumber, + CreateConversationRequest, + CreateMessageRequest, + GetConversationRequest, + ListConversationsRequest, + ListConversationsResponse, + ListMessagesRequest, + ListMessagesResponse, +) +from .conversation_event import ( + ConversationEvent, +) +from .conversation_profile import ( + AutomatedAgentConfig, + ConversationProfile, + CreateConversationProfileRequest, + DeleteConversationProfileRequest, + GetConversationProfileRequest, + HumanAgentAssistantConfig, + HumanAgentHandoffConfig, + ListConversationProfilesRequest, + ListConversationProfilesResponse, + LoggingConfig, + NotificationConfig, + UpdateConversationProfileRequest, +) +from .document import ( + CreateDocumentRequest, + DeleteDocumentRequest, + Document, + GetDocumentRequest, + ImportDocumentsRequest, + ImportDocumentsResponse, + ImportDocumentTemplate, + KnowledgeOperationMetadata, + ListDocumentsRequest, + ListDocumentsResponse, + ReloadDocumentRequest, + UpdateDocumentRequest, +) +from .entity_type import ( + BatchCreateEntitiesRequest, + BatchDeleteEntitiesRequest, + BatchDeleteEntityTypesRequest, + BatchUpdateEntitiesRequest, + BatchUpdateEntityTypesRequest, + BatchUpdateEntityTypesResponse, + CreateEntityTypeRequest, + DeleteEntityTypeRequest, + EntityType, + EntityTypeBatch, + GetEntityTypeRequest, + ListEntityTypesRequest, + ListEntityTypesResponse, + UpdateEntityTypeRequest, +) +from .environment import ( + CreateEnvironmentRequest, + DeleteEnvironmentRequest, + Environment, + EnvironmentHistory, + GetEnvironmentHistoryRequest, + GetEnvironmentRequest, + ListEnvironmentsRequest, + ListEnvironmentsResponse, + TextToSpeechSettings, + UpdateEnvironmentRequest, +) +from .fulfillment import ( + Fulfillment, + GetFulfillmentRequest, + UpdateFulfillmentRequest, +) +from .gcs import ( + GcsSource, + GcsSources, +) +from .human_agent_assistant_event import ( + HumanAgentAssistantEvent, +) +from .intent import ( + BatchDeleteIntentsRequest, + BatchUpdateIntentsRequest, + BatchUpdateIntentsResponse, + CreateIntentRequest, + DeleteIntentRequest, + GetIntentRequest, + Intent, + IntentBatch, + ListIntentsRequest, + ListIntentsResponse, + UpdateIntentRequest, + IntentView, +) +from .knowledge_base import ( + CreateKnowledgeBaseRequest, + DeleteKnowledgeBaseRequest, + GetKnowledgeBaseRequest, + KnowledgeBase, + ListKnowledgeBasesRequest, + ListKnowledgeBasesResponse, + UpdateKnowledgeBaseRequest, +) +from .participant import ( + AnalyzeContentRequest, + AnalyzeContentResponse, + AnnotatedMessagePart, + ArticleAnswer, + AssistQueryParameters, + AutomatedAgentReply, + CompileSuggestionRequest, + CompileSuggestionResponse, + CreateParticipantRequest, + DtmfParameters, + FaqAnswer, + GetParticipantRequest, + ListParticipantsRequest, + ListParticipantsResponse, + ListSuggestionsRequest, + ListSuggestionsResponse, + Message, + MessageAnnotation, + OutputAudio, + Participant, + ResponseMessage, + SmartReplyAnswer, + SuggestArticlesRequest, + SuggestArticlesResponse, + SuggestFaqAnswersRequest, + SuggestFaqAnswersResponse, + Suggestion, + SuggestionFeature, + SuggestionResult, + SuggestSmartRepliesRequest, + SuggestSmartRepliesResponse, + UpdateParticipantRequest, +) +from .session import ( + DetectIntentRequest, + DetectIntentResponse, + EventInput, + KnowledgeAnswers, + QueryInput, + QueryParameters, + QueryResult, + Sentiment, + SentimentAnalysisRequestConfig, + SentimentAnalysisResult, + StreamingDetectIntentRequest, + StreamingDetectIntentResponse, + StreamingRecognitionResult, + TextInput, +) +from .session_entity_type import ( + CreateSessionEntityTypeRequest, + DeleteSessionEntityTypeRequest, + GetSessionEntityTypeRequest, + ListSessionEntityTypesRequest, + ListSessionEntityTypesResponse, + SessionEntityType, + UpdateSessionEntityTypeRequest, +) +from .validation_result import ( + ValidationError, + ValidationResult, +) +from .version import ( + CreateVersionRequest, + DeleteVersionRequest, + GetVersionRequest, + ListVersionsRequest, + ListVersionsResponse, + UpdateVersionRequest, + Version, +) +from .webhook import ( + OriginalDetectIntentRequest, + WebhookRequest, + WebhookResponse, +) + +__all__ = ( + 'Agent', + 'DeleteAgentRequest', + 'ExportAgentRequest', + 'ExportAgentResponse', + 'GetAgentRequest', + 'GetValidationResultRequest', + 'ImportAgentRequest', + 'RestoreAgentRequest', + 'SearchAgentsRequest', + 'SearchAgentsResponse', + 'SetAgentRequest', + 'SubAgent', + 'TrainAgentRequest', + 'AgentAssistantFeedback', + 'AgentAssistantRecord', + 'AnswerFeedback', + 'AnswerRecord', + 'GetAnswerRecordRequest', + 'ListAnswerRecordsRequest', + 'ListAnswerRecordsResponse', + 'UpdateAnswerRecordRequest', + 'InputAudioConfig', + 'OutputAudioConfig', + 'SpeechContext', + 'SpeechToTextConfig', + 'SpeechWordInfo', + 'SynthesizeSpeechConfig', + 'TelephonyDtmfEvents', + 'VoiceSelectionParams', + 'AudioEncoding', + 'OutputAudioEncoding', + 'SpeechModelVariant', + 'SsmlVoiceGender', + 'TelephonyDtmf', + 'Context', + 'CreateContextRequest', + 'DeleteAllContextsRequest', + 'DeleteContextRequest', + 'GetContextRequest', + 'ListContextsRequest', + 'ListContextsResponse', + 'UpdateContextRequest', + 'BatchCreateMessagesRequest', + 'BatchCreateMessagesResponse', + 'CompleteConversationRequest', + 'Conversation', + 'ConversationPhoneNumber', + 'CreateConversationRequest', + 'CreateMessageRequest', + 'GetConversationRequest', + 'ListConversationsRequest', + 'ListConversationsResponse', + 'ListMessagesRequest', + 'ListMessagesResponse', + 'ConversationEvent', + 'AutomatedAgentConfig', + 'ConversationProfile', + 'CreateConversationProfileRequest', + 'DeleteConversationProfileRequest', + 'GetConversationProfileRequest', + 'HumanAgentAssistantConfig', + 'HumanAgentHandoffConfig', + 'ListConversationProfilesRequest', + 'ListConversationProfilesResponse', + 'LoggingConfig', + 'NotificationConfig', + 'UpdateConversationProfileRequest', + 'CreateDocumentRequest', + 'DeleteDocumentRequest', + 'Document', + 'GetDocumentRequest', + 'ImportDocumentsRequest', + 'ImportDocumentsResponse', + 'ImportDocumentTemplate', + 'KnowledgeOperationMetadata', + 'ListDocumentsRequest', + 'ListDocumentsResponse', + 'ReloadDocumentRequest', + 'UpdateDocumentRequest', + 'BatchCreateEntitiesRequest', + 'BatchDeleteEntitiesRequest', + 'BatchDeleteEntityTypesRequest', + 'BatchUpdateEntitiesRequest', + 'BatchUpdateEntityTypesRequest', + 'BatchUpdateEntityTypesResponse', + 'CreateEntityTypeRequest', + 'DeleteEntityTypeRequest', + 'EntityType', + 'EntityTypeBatch', + 'GetEntityTypeRequest', + 'ListEntityTypesRequest', + 'ListEntityTypesResponse', + 'UpdateEntityTypeRequest', + 'CreateEnvironmentRequest', + 'DeleteEnvironmentRequest', + 'Environment', + 'EnvironmentHistory', + 'GetEnvironmentHistoryRequest', + 'GetEnvironmentRequest', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'TextToSpeechSettings', + 'UpdateEnvironmentRequest', + 'Fulfillment', + 'GetFulfillmentRequest', + 'UpdateFulfillmentRequest', + 'GcsSource', + 'GcsSources', + 'HumanAgentAssistantEvent', + 'BatchDeleteIntentsRequest', + 'BatchUpdateIntentsRequest', + 'BatchUpdateIntentsResponse', + 'CreateIntentRequest', + 'DeleteIntentRequest', + 'GetIntentRequest', + 'Intent', + 'IntentBatch', + 'ListIntentsRequest', + 'ListIntentsResponse', + 'UpdateIntentRequest', + 'IntentView', + 'CreateKnowledgeBaseRequest', + 'DeleteKnowledgeBaseRequest', + 'GetKnowledgeBaseRequest', + 'KnowledgeBase', + 'ListKnowledgeBasesRequest', + 'ListKnowledgeBasesResponse', + 'UpdateKnowledgeBaseRequest', + 'AnalyzeContentRequest', + 'AnalyzeContentResponse', + 'AnnotatedMessagePart', + 'ArticleAnswer', + 'AssistQueryParameters', + 'AutomatedAgentReply', + 'CompileSuggestionRequest', + 'CompileSuggestionResponse', + 'CreateParticipantRequest', + 'DtmfParameters', + 'FaqAnswer', + 'GetParticipantRequest', + 'ListParticipantsRequest', + 'ListParticipantsResponse', + 'ListSuggestionsRequest', + 'ListSuggestionsResponse', + 'Message', + 'MessageAnnotation', + 'OutputAudio', + 'Participant', + 'ResponseMessage', + 'SmartReplyAnswer', + 'SuggestArticlesRequest', + 'SuggestArticlesResponse', + 'SuggestFaqAnswersRequest', + 'SuggestFaqAnswersResponse', + 'Suggestion', + 'SuggestionFeature', + 'SuggestionResult', + 'SuggestSmartRepliesRequest', + 'SuggestSmartRepliesResponse', + 'UpdateParticipantRequest', + 'DetectIntentRequest', + 'DetectIntentResponse', + 'EventInput', + 'KnowledgeAnswers', + 'QueryInput', + 'QueryParameters', + 'QueryResult', + 'Sentiment', + 'SentimentAnalysisRequestConfig', + 'SentimentAnalysisResult', + 'StreamingDetectIntentRequest', + 'StreamingDetectIntentResponse', + 'StreamingRecognitionResult', + 'TextInput', + 'CreateSessionEntityTypeRequest', + 'DeleteSessionEntityTypeRequest', + 'GetSessionEntityTypeRequest', + 'ListSessionEntityTypesRequest', + 'ListSessionEntityTypesResponse', + 'SessionEntityType', + 'UpdateSessionEntityTypeRequest', + 'ValidationError', + 'ValidationResult', + 'CreateVersionRequest', + 'DeleteVersionRequest', + 'GetVersionRequest', + 'ListVersionsRequest', + 'ListVersionsResponse', + 'UpdateVersionRequest', + 'Version', + 'OriginalDetectIntentRequest', + 'WebhookRequest', + 'WebhookResponse', +) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/agent.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/agent.py new file mode 100644 index 000000000..d7bedd94c --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/agent.py @@ -0,0 +1,526 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2beta1', + manifest={ + 'Agent', + 'GetAgentRequest', + 'SetAgentRequest', + 'DeleteAgentRequest', + 'SubAgent', + 'SearchAgentsRequest', + 'SearchAgentsResponse', + 'TrainAgentRequest', + 'ExportAgentRequest', + 'ExportAgentResponse', + 'ImportAgentRequest', + 'RestoreAgentRequest', + 'GetValidationResultRequest', + }, +) + + +class Agent(proto.Message): + r"""A Dialogflow agent is a virtual agent that handles conversations + with your end-users. It is a natural language understanding module + that understands the nuances of human language. Dialogflow + translates end-user text or audio during a conversation to + structured data that your apps and services can understand. You + design and build a Dialogflow agent to handle the types of + conversations required for your system. + + For more information about agents, see the `Agent + guide `__. + + Attributes: + parent (str): + Required. The project of this agent. Format: + ``projects/`` or + ``projects//locations/`` + display_name (str): + Required. The name of this agent. + default_language_code (str): + Required. The default language of the agent as a language + tag. See `Language + Support `__ + for a list of the currently supported language codes. This + field cannot be set by the ``Update`` method. + supported_language_codes (Sequence[str]): + Optional. The list of all languages supported by this agent + (except for the ``default_language_code``). + time_zone (str): + Required. The time zone of this agent from the `time zone + database `__, e.g., + America/New_York, Europe/Paris. + description (str): + Optional. The description of this agent. + The maximum length is 500 characters. If + exceeded, the request is rejected. + avatar_uri (str): + Optional. The URI of the agent's avatar. Avatars are used + throughout the Dialogflow console and in the self-hosted + `Web + Demo `__ + integration. + enable_logging (bool): + Optional. Determines whether this agent + should log conversation queries. + match_mode (google.cloud.dialogflow_v2beta1.types.Agent.MatchMode): + Optional. Determines how intents are detected + from user queries. + classification_threshold (float): + Optional. To filter out false positive + results and still get variety in matched natural + language inputs for your agent, you can tune the + machine learning classification threshold. If + the returned score value is less than the + threshold value, then a fallback intent will be + triggered or, if there are no fallback intents + defined, no intent will be triggered. The score + values range from 0.0 (completely uncertain) to + 1.0 (completely certain). If set to 0.0, the + default of 0.3 is used. + api_version (google.cloud.dialogflow_v2beta1.types.Agent.ApiVersion): + Optional. API version displayed in Dialogflow + console. If not specified, V2 API is assumed. + Clients are free to query different service + endpoints for different API versions. However, + bots connectors and webhook calls will follow + the specified API version. + tier (google.cloud.dialogflow_v2beta1.types.Agent.Tier): + Optional. The agent tier. If not specified, TIER_STANDARD is + assumed. + """ + class MatchMode(proto.Enum): + r"""Match mode determines how intents are detected from user + queries. + """ + MATCH_MODE_UNSPECIFIED = 0 + MATCH_MODE_HYBRID = 1 + MATCH_MODE_ML_ONLY = 2 + + class ApiVersion(proto.Enum): + r"""API version for the agent.""" + API_VERSION_UNSPECIFIED = 0 + API_VERSION_V1 = 1 + API_VERSION_V2 = 2 + API_VERSION_V2_BETA_1 = 3 + + class Tier(proto.Enum): + r"""Represents the agent tier.""" + TIER_UNSPECIFIED = 0 + TIER_STANDARD = 1 + TIER_ENTERPRISE = 2 + TIER_ENTERPRISE_PLUS = 3 + + parent = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + default_language_code = proto.Field( + proto.STRING, + number=3, + ) + supported_language_codes = proto.RepeatedField( + proto.STRING, + number=4, + ) + time_zone = proto.Field( + proto.STRING, + number=5, + ) + description = proto.Field( + proto.STRING, + number=6, + ) + avatar_uri = proto.Field( + proto.STRING, + number=7, + ) + enable_logging = proto.Field( + proto.BOOL, + number=8, + ) + match_mode = proto.Field( + proto.ENUM, + number=9, + enum=MatchMode, + ) + classification_threshold = proto.Field( + proto.FLOAT, + number=10, + ) + api_version = proto.Field( + proto.ENUM, + number=14, + enum=ApiVersion, + ) + tier = proto.Field( + proto.ENUM, + number=15, + enum=Tier, + ) + + +class GetAgentRequest(proto.Message): + r"""The request message for + [Agents.GetAgent][google.cloud.dialogflow.v2beta1.Agents.GetAgent]. + + Attributes: + parent (str): + Required. The project that the agent to fetch is associated + with. Format: ``projects/`` or + ``projects//locations/``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + + +class SetAgentRequest(proto.Message): + r"""The request message for + [Agents.SetAgent][google.cloud.dialogflow.v2beta1.Agents.SetAgent]. + + Attributes: + agent (google.cloud.dialogflow_v2beta1.types.Agent): + Required. The agent to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which fields + get updated. + """ + + agent = proto.Field( + proto.MESSAGE, + number=1, + message='Agent', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteAgentRequest(proto.Message): + r"""The request message for + [Agents.DeleteAgent][google.cloud.dialogflow.v2beta1.Agents.DeleteAgent]. + + Attributes: + parent (str): + Required. The project that the agent to delete is associated + with. Format: ``projects/`` or + ``projects//locations/``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + + +class SubAgent(proto.Message): + r"""Contains basic configuration for a sub-agent. + + Attributes: + project (str): + Required. The project of this agent. Format: + ``projects/`` or + ``projects//locations/``. + environment (str): + Optional. The unique identifier (``environment name`` in + dialogflow console) of this sub-agent environment. Assumes + draft environment if ``environment`` is not set. + """ + + project = proto.Field( + proto.STRING, + number=1, + ) + environment = proto.Field( + proto.STRING, + number=2, + ) + + +class SearchAgentsRequest(proto.Message): + r"""The request message for + [Agents.SearchAgents][google.cloud.dialogflow.v2beta1.Agents.SearchAgents]. + + Attributes: + parent (str): + Required. The project to list agents from. Format: + ``projects/`` or + ``projects//locations/``. + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class SearchAgentsResponse(proto.Message): + r"""The response message for + [Agents.SearchAgents][google.cloud.dialogflow.v2beta1.Agents.SearchAgents]. + + Attributes: + agents (Sequence[google.cloud.dialogflow_v2beta1.types.Agent]): + The list of agents. There will be a maximum number of items + returned based on the page_size field in the request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + agents = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Agent', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class TrainAgentRequest(proto.Message): + r"""The request message for + [Agents.TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent]. + + Attributes: + parent (str): + Required. The project that the agent to train is associated + with. Format: ``projects/`` or + ``projects//locations/``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + + +class ExportAgentRequest(proto.Message): + r"""The request message for + [Agents.ExportAgent][google.cloud.dialogflow.v2beta1.Agents.ExportAgent]. + + Attributes: + parent (str): + Required. The project that the agent to export is associated + with. Format: ``projects/`` or + ``projects//locations/``. + agent_uri (str): + Optional. The `Google Cloud + Storage `__ URI to + export the agent to. The format of this URI must be + ``gs:///``. If left unspecified, + the serialized agent is returned inline. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + agent_uri = proto.Field( + proto.STRING, + number=2, + ) + + +class ExportAgentResponse(proto.Message): + r"""The response message for + [Agents.ExportAgent][google.cloud.dialogflow.v2beta1.Agents.ExportAgent]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + agent_uri (str): + The URI to a file containing the exported agent. This field + is populated only if ``agent_uri`` is specified in + ``ExportAgentRequest``. + + This field is a member of `oneof`_ ``agent``. + agent_content (bytes): + Zip compressed raw byte content for agent. + + This field is a member of `oneof`_ ``agent``. + """ + + agent_uri = proto.Field( + proto.STRING, + number=1, + oneof='agent', + ) + agent_content = proto.Field( + proto.BYTES, + number=2, + oneof='agent', + ) + + +class ImportAgentRequest(proto.Message): + r"""The request message for + [Agents.ImportAgent][google.cloud.dialogflow.v2beta1.Agents.ImportAgent]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The project that the agent to import is associated + with. Format: ``projects/`` or + ``projects//locations/``. + agent_uri (str): + The URI to a Google Cloud Storage file + containing the agent to import. Note: The URI + must start with "gs://". + + This field is a member of `oneof`_ ``agent``. + agent_content (bytes): + Zip compressed raw byte content for agent. + + This field is a member of `oneof`_ ``agent``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + agent_uri = proto.Field( + proto.STRING, + number=2, + oneof='agent', + ) + agent_content = proto.Field( + proto.BYTES, + number=3, + oneof='agent', + ) + + +class RestoreAgentRequest(proto.Message): + r"""The request message for + [Agents.RestoreAgent][google.cloud.dialogflow.v2beta1.Agents.RestoreAgent]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The project that the agent to restore is + associated with. Format: ``projects/`` or + ``projects//locations/``. + agent_uri (str): + The URI to a Google Cloud Storage file + containing the agent to restore. Note: The URI + must start with "gs://". + + This field is a member of `oneof`_ ``agent``. + agent_content (bytes): + Zip compressed raw byte content for agent. + + This field is a member of `oneof`_ ``agent``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + agent_uri = proto.Field( + proto.STRING, + number=2, + oneof='agent', + ) + agent_content = proto.Field( + proto.BYTES, + number=3, + oneof='agent', + ) + + +class GetValidationResultRequest(proto.Message): + r"""The request message for + [Agents.GetValidationResult][google.cloud.dialogflow.v2beta1.Agents.GetValidationResult]. + + Attributes: + parent (str): + Required. The project that the agent is associated with. + Format: ``projects/`` or + ``projects//locations/``. + language_code (str): + Optional. The language for which you want a validation + result. If not specified, the agent's default language is + used. `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/answer_record.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/answer_record.py new file mode 100644 index 000000000..fb755f730 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/answer_record.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 proto # type: ignore + +from google.cloud.dialogflow_v2beta1.types import participant +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2beta1', + manifest={ + 'AnswerRecord', + 'AgentAssistantRecord', + 'AnswerFeedback', + 'AgentAssistantFeedback', + 'GetAnswerRecordRequest', + 'ListAnswerRecordsRequest', + 'ListAnswerRecordsResponse', + 'UpdateAnswerRecordRequest', + }, +) + + +class AnswerRecord(proto.Message): + r"""Answer records are records to manage answer history and feedbacks + for Dialogflow. + + Currently, answer record includes: + + - human agent assistant article suggestion + - human agent assistant faq article + + It doesn't include: + + - ``DetectIntent`` intent matching + - ``DetectIntent`` knowledge + + Answer records are not related to the conversation history in the + Dialogflow Console. A Record is generated even when the end-user + disables conversation history in the console. Records are created + when there's a human agent assistant suggestion generated. + + A typical workflow for customers provide feedback to an answer is: + + 1. For human agent assistant, customers get suggestion via + ListSuggestions API. Together with the answers, + [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] + are returned to the customers. + 2. The customer uses the + [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] + to call the [UpdateAnswerRecord][] method to send feedback about + a specific answer that they believe is wrong. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + The unique identifier of this answer record. Required for + [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.UpdateAnswerRecord] + method. Format: + ``projects//locations//answerRecords/``. + answer_feedback (google.cloud.dialogflow_v2beta1.types.AnswerFeedback): + Optional. The AnswerFeedback for this record. You can set + this with + [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.UpdateAnswerRecord] + in order to give us feedback about this answer. + agent_assistant_record (google.cloud.dialogflow_v2beta1.types.AgentAssistantRecord): + Output only. The record for human agent + assistant. + + This field is a member of `oneof`_ ``record``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + answer_feedback = proto.Field( + proto.MESSAGE, + number=3, + message='AnswerFeedback', + ) + agent_assistant_record = proto.Field( + proto.MESSAGE, + number=4, + oneof='record', + message='AgentAssistantRecord', + ) + + +class AgentAssistantRecord(proto.Message): + r"""Represents a record of a human agent assistant answer. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + article_suggestion_answer (google.cloud.dialogflow_v2beta1.types.ArticleAnswer): + Output only. The article suggestion answer. + + This field is a member of `oneof`_ ``answer``. + faq_answer (google.cloud.dialogflow_v2beta1.types.FaqAnswer): + Output only. The FAQ answer. + + This field is a member of `oneof`_ ``answer``. + """ + + article_suggestion_answer = proto.Field( + proto.MESSAGE, + number=5, + oneof='answer', + message=participant.ArticleAnswer, + ) + faq_answer = proto.Field( + proto.MESSAGE, + number=6, + oneof='answer', + message=participant.FaqAnswer, + ) + + +class AnswerFeedback(proto.Message): + r"""Represents feedback the customer has about the quality & + correctness of a certain answer in a conversation. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + correctness_level (google.cloud.dialogflow_v2beta1.types.AnswerFeedback.CorrectnessLevel): + The correctness level of the specific answer. + agent_assistant_detail_feedback (google.cloud.dialogflow_v2beta1.types.AgentAssistantFeedback): + Optional. Detail feedback of agent assistant + suggestions. + + This field is a member of `oneof`_ ``detail_feedback``. + clicked (bool): + Indicates whether the answer/item was clicked + by the human agent or not. Default to false. + click_time (google.protobuf.timestamp_pb2.Timestamp): + Time when the answer/item was clicked. + displayed (bool): + Indicates whether the answer/item was + displayed to the human agent in the agent + desktop UI. Default to false. + display_time (google.protobuf.timestamp_pb2.Timestamp): + Time when the answer/item was displayed. + """ + class CorrectnessLevel(proto.Enum): + r"""The correctness level of an answer.""" + CORRECTNESS_LEVEL_UNSPECIFIED = 0 + NOT_CORRECT = 1 + PARTIALLY_CORRECT = 2 + FULLY_CORRECT = 3 + + correctness_level = proto.Field( + proto.ENUM, + number=1, + enum=CorrectnessLevel, + ) + agent_assistant_detail_feedback = proto.Field( + proto.MESSAGE, + number=2, + oneof='detail_feedback', + message='AgentAssistantFeedback', + ) + clicked = proto.Field( + proto.BOOL, + number=3, + ) + click_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + displayed = proto.Field( + proto.BOOL, + number=4, + ) + display_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + +class AgentAssistantFeedback(proto.Message): + r"""Detail feedback of Agent Assistant result. + + Attributes: + answer_relevance (google.cloud.dialogflow_v2beta1.types.AgentAssistantFeedback.AnswerRelevance): + Optional. Whether or not the suggested answer is relevant. + + For example: + + - Query: "Can I change my mailing address?" + - Suggested document says: "Items must be + returned/exchanged within 60 days of the purchase date." + - [answer_relevance][google.cloud.dialogflow.v2beta1.AgentAssistantFeedback.answer_relevance]: + [AnswerRelevance.IRRELEVANT][google.cloud.dialogflow.v2beta1.AgentAssistantFeedback.AnswerRelevance.IRRELEVANT] + document_correctness (google.cloud.dialogflow_v2beta1.types.AgentAssistantFeedback.DocumentCorrectness): + Optional. Whether or not the information in the document is + correct. + + For example: + + - Query: "Can I return the package in 2 days once + received?" + - Suggested document says: "Items must be + returned/exchanged within 60 days of the purchase date." + - Ground truth: "No return or exchange is allowed." + - + document_efficiency (google.cloud.dialogflow_v2beta1.types.AgentAssistantFeedback.DocumentEfficiency): + Optional. Whether or not the suggested document is + efficient. For example, if the document is poorly written, + hard to understand, hard to use or too long to find useful + information, + [document_efficiency][google.cloud.dialogflow.v2beta1.AgentAssistantFeedback.document_efficiency] + is + [DocumentEfficiency.INEFFICIENT][google.cloud.dialogflow.v2beta1.AgentAssistantFeedback.DocumentEfficiency.INEFFICIENT]. + summarization_feedback (google.cloud.dialogflow_v2beta1.types.AgentAssistantFeedback.SummarizationFeedback): + Feedback for conversation summarization. + """ + class AnswerRelevance(proto.Enum): + r"""Relevance of an answer.""" + ANSWER_RELEVANCE_UNSPECIFIED = 0 + IRRELEVANT = 1 + RELEVANT = 2 + + class DocumentCorrectness(proto.Enum): + r"""Correctness of document.""" + DOCUMENT_CORRECTNESS_UNSPECIFIED = 0 + INCORRECT = 1 + CORRECT = 2 + + class DocumentEfficiency(proto.Enum): + r"""Efficiency of document.""" + DOCUMENT_EFFICIENCY_UNSPECIFIED = 0 + INEFFICIENT = 1 + EFFICIENT = 2 + + class SummarizationFeedback(proto.Message): + r"""Feedback for conversation summarization. + + Attributes: + start_timestamp (google.protobuf.timestamp_pb2.Timestamp): + Timestamp when composing of the summary + starts. + submit_timestamp (google.protobuf.timestamp_pb2.Timestamp): + Timestamp when the summary was submitted. + summary_text (str): + Text of actual submitted summary. + """ + + start_timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + submit_timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + summary_text = proto.Field( + proto.STRING, + number=3, + ) + + answer_relevance = proto.Field( + proto.ENUM, + number=1, + enum=AnswerRelevance, + ) + document_correctness = proto.Field( + proto.ENUM, + number=2, + enum=DocumentCorrectness, + ) + document_efficiency = proto.Field( + proto.ENUM, + number=3, + enum=DocumentEfficiency, + ) + summarization_feedback = proto.Field( + proto.MESSAGE, + number=4, + message=SummarizationFeedback, + ) + + +class GetAnswerRecordRequest(proto.Message): + r"""Request message for + [AnswerRecords.GetAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.GetAnswerRecord]. + + Attributes: + name (str): + Required. The name of the answer record to retrieve. Format: + ``projects//locations//answerRecords/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListAnswerRecordsRequest(proto.Message): + r"""Request message for + [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. + + Attributes: + parent (str): + Required. The project to list all answer records for in + reverse chronological order. Format: + ``projects//locations/``. + page_size (int): + Optional. The maximum number of records to + return in a single page. The server may return + fewer records than this. If unspecified, we use + 10. The maximum is 100. + page_token (str): + Optional. The + [ListAnswerRecordsResponse.next_page_token][google.cloud.dialogflow.v2beta1.ListAnswerRecordsResponse.next_page_token] + value returned from a previous list request used to continue + listing on the next page. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class ListAnswerRecordsResponse(proto.Message): + r"""Response message for + [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. + + Attributes: + answer_records (Sequence[google.cloud.dialogflow_v2beta1.types.AnswerRecord]): + The list of answer records. + next_page_token (str): + A token to retrieve next page of results. Or empty if there + are no more results. Pass this value in the + [ListAnswerRecordsRequest.page_token][google.cloud.dialogflow.v2beta1.ListAnswerRecordsRequest.page_token] + field in the subsequent call to ``ListAnswerRecords`` method + to retrieve the next page of results. + """ + + @property + def raw_page(self): + return self + + answer_records = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AnswerRecord', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateAnswerRecordRequest(proto.Message): + r"""Request message for + [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.UpdateAnswerRecord]. + + Attributes: + answer_record (google.cloud.dialogflow_v2beta1.types.AnswerRecord): + Required. Answer record to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. + """ + + answer_record = proto.Field( + proto.MESSAGE, + number=1, + message='AnswerRecord', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/audio_config.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/audio_config.py new file mode 100644 index 000000000..77d7919c9 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/audio_config.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.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2beta1', + manifest={ + 'AudioEncoding', + 'SpeechModelVariant', + 'SsmlVoiceGender', + 'OutputAudioEncoding', + 'TelephonyDtmf', + 'SpeechContext', + 'SpeechWordInfo', + 'InputAudioConfig', + 'VoiceSelectionParams', + 'SynthesizeSpeechConfig', + 'OutputAudioConfig', + 'TelephonyDtmfEvents', + 'SpeechToTextConfig', + }, +) + + +class AudioEncoding(proto.Enum): + r"""Audio encoding of the audio content sent in the conversational query + request. Refer to the `Cloud Speech API + documentation `__ + for more details. + """ + AUDIO_ENCODING_UNSPECIFIED = 0 + AUDIO_ENCODING_LINEAR_16 = 1 + AUDIO_ENCODING_FLAC = 2 + AUDIO_ENCODING_MULAW = 3 + AUDIO_ENCODING_AMR = 4 + AUDIO_ENCODING_AMR_WB = 5 + AUDIO_ENCODING_OGG_OPUS = 6 + AUDIO_ENCODING_SPEEX_WITH_HEADER_BYTE = 7 + + +class SpeechModelVariant(proto.Enum): + r"""Variant of the specified [Speech + model][google.cloud.dialogflow.v2beta1.InputAudioConfig.model] to + use. + + See the `Cloud Speech + documentation `__ + for which models have different variants. For example, the + "phone_call" model has both a standard and an enhanced variant. When + you use an enhanced model, you will generally receive higher quality + results than for a standard model. + """ + SPEECH_MODEL_VARIANT_UNSPECIFIED = 0 + USE_BEST_AVAILABLE = 1 + USE_STANDARD = 2 + USE_ENHANCED = 3 + + +class SsmlVoiceGender(proto.Enum): + r"""Gender of the voice as described in `SSML voice + element `__. + """ + SSML_VOICE_GENDER_UNSPECIFIED = 0 + SSML_VOICE_GENDER_MALE = 1 + SSML_VOICE_GENDER_FEMALE = 2 + SSML_VOICE_GENDER_NEUTRAL = 3 + + +class OutputAudioEncoding(proto.Enum): + r"""Audio encoding of the output audio format in Text-To-Speech.""" + OUTPUT_AUDIO_ENCODING_UNSPECIFIED = 0 + OUTPUT_AUDIO_ENCODING_LINEAR_16 = 1 + OUTPUT_AUDIO_ENCODING_MP3 = 2 + OUTPUT_AUDIO_ENCODING_MP3_64_KBPS = 4 + OUTPUT_AUDIO_ENCODING_OGG_OPUS = 3 + OUTPUT_AUDIO_ENCODING_MULAW = 5 + + +class TelephonyDtmf(proto.Enum): + r"""`DTMF `__ + digit in Telephony Gateway. + """ + TELEPHONY_DTMF_UNSPECIFIED = 0 + DTMF_ONE = 1 + DTMF_TWO = 2 + DTMF_THREE = 3 + DTMF_FOUR = 4 + DTMF_FIVE = 5 + DTMF_SIX = 6 + DTMF_SEVEN = 7 + DTMF_EIGHT = 8 + DTMF_NINE = 9 + DTMF_ZERO = 10 + DTMF_A = 11 + DTMF_B = 12 + DTMF_C = 13 + DTMF_D = 14 + DTMF_STAR = 15 + DTMF_POUND = 16 + + +class SpeechContext(proto.Message): + r"""Hints for the speech recognizer to help with recognition in a + specific conversation state. + + Attributes: + phrases (Sequence[str]): + Optional. A list of strings containing words and phrases + that the speech recognizer should recognize with higher + likelihood. + + This list can be used to: + + - improve accuracy for words and phrases you expect the + user to say, e.g. typical commands for your Dialogflow + agent + - add additional words to the speech recognizer vocabulary + - ... + + See the `Cloud Speech + documentation `__ + for usage limits. + boost (float): + Optional. Boost for this context compared to other contexts: + + - If the boost is positive, Dialogflow will increase the + probability that the phrases in this context are + recognized over similar sounding phrases. + - If the boost is unspecified or non-positive, Dialogflow + will not apply any boost. + + Dialogflow recommends that you use boosts in the range (0, + 20] and that you find a value that fits your use case with + binary search. + """ + + phrases = proto.RepeatedField( + proto.STRING, + number=1, + ) + boost = proto.Field( + proto.FLOAT, + number=2, + ) + + +class SpeechWordInfo(proto.Message): + r"""Information for a word recognized by the speech recognizer. + + Attributes: + word (str): + The word this info is for. + start_offset (google.protobuf.duration_pb2.Duration): + Time offset relative to the beginning of the + audio that corresponds to the start of the + spoken word. This is an experimental feature and + the accuracy of the time offset can vary. + end_offset (google.protobuf.duration_pb2.Duration): + Time offset relative to the beginning of the + audio that corresponds to the end of the spoken + word. This is an experimental feature and the + accuracy of the time offset can vary. + confidence (float): + The Speech confidence between 0.0 and 1.0 for + this word. A higher number indicates an + estimated greater likelihood that the recognized + word is correct. The default of 0.0 is a + sentinel value indicating that confidence was + not set. + + This field is not guaranteed to be fully stable + over time for the same audio input. Users should + also not rely on it to always be provided. + """ + + word = proto.Field( + proto.STRING, + number=3, + ) + start_offset = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + end_offset = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + confidence = proto.Field( + proto.FLOAT, + number=4, + ) + + +class InputAudioConfig(proto.Message): + r"""Instructs the speech recognizer on how to process the audio + content. + + Attributes: + audio_encoding (google.cloud.dialogflow_v2beta1.types.AudioEncoding): + Required. Audio encoding of the audio content + to process. + sample_rate_hertz (int): + Required. Sample rate (in Hertz) of the audio content sent + in the query. Refer to `Cloud Speech API + documentation `__ + for more details. + language_code (str): + Required. The language of the supplied audio. Dialogflow + does not do translations. See `Language + Support `__ + for a list of the currently supported language codes. Note + that queries in the same session do not necessarily need to + specify the same language. + enable_word_info (bool): + If ``true``, Dialogflow returns + [SpeechWordInfo][google.cloud.dialogflow.v2beta1.SpeechWordInfo] + in + [StreamingRecognitionResult][google.cloud.dialogflow.v2beta1.StreamingRecognitionResult] + with information about the recognized speech words, e.g. + start and end time offsets. If false or unspecified, Speech + doesn't return any word-level information. + phrase_hints (Sequence[str]): + A list of strings containing words and phrases that the + speech recognizer should recognize with higher likelihood. + + See `the Cloud Speech + documentation `__ + for more details. + + This field is deprecated. Please use `speech_contexts <>`__ + instead. If you specify both `phrase_hints <>`__ and + `speech_contexts <>`__, Dialogflow will treat the + `phrase_hints <>`__ as a single additional + `SpeechContext <>`__. + speech_contexts (Sequence[google.cloud.dialogflow_v2beta1.types.SpeechContext]): + Context information to assist speech recognition. + + See `the Cloud Speech + documentation `__ + for more details. + model (str): + Which Speech model to select for the given request. Select + the model best suited to your domain to get best results. If + a model is not explicitly specified, then we auto-select a + model based on the parameters in the InputAudioConfig. If + enhanced speech model is enabled for the agent and an + enhanced version of the specified model for the language + does not exist, then the speech is recognized using the + standard version of the specified model. Refer to `Cloud + Speech API + documentation `__ + for more details. + model_variant (google.cloud.dialogflow_v2beta1.types.SpeechModelVariant): + Which variant of the [Speech + model][google.cloud.dialogflow.v2beta1.InputAudioConfig.model] + to use. + single_utterance (bool): + If ``false`` (default), recognition does not cease until the + client closes the stream. If ``true``, the recognizer will + detect a single spoken utterance in input audio. Recognition + ceases when it detects the audio's voice has stopped or + paused. In this case, once a detected intent is received, + the client should close the stream and start a new request + with a new stream as needed. Note: This setting is relevant + only for streaming methods. Note: When specified, + InputAudioConfig.single_utterance takes precedence over + StreamingDetectIntentRequest.single_utterance. + disable_no_speech_recognized_event (bool): + Only used in + [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent] + and + [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.StreamingAnalyzeContent]. + If ``false`` and recognition doesn't return any result, + trigger ``NO_SPEECH_RECOGNIZED`` event to Dialogflow agent. + """ + + audio_encoding = proto.Field( + proto.ENUM, + number=1, + enum='AudioEncoding', + ) + sample_rate_hertz = proto.Field( + proto.INT32, + number=2, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + enable_word_info = proto.Field( + proto.BOOL, + number=13, + ) + phrase_hints = proto.RepeatedField( + proto.STRING, + number=4, + ) + speech_contexts = proto.RepeatedField( + proto.MESSAGE, + number=11, + message='SpeechContext', + ) + model = proto.Field( + proto.STRING, + number=7, + ) + model_variant = proto.Field( + proto.ENUM, + number=10, + enum='SpeechModelVariant', + ) + single_utterance = proto.Field( + proto.BOOL, + number=8, + ) + disable_no_speech_recognized_event = proto.Field( + proto.BOOL, + number=14, + ) + + +class VoiceSelectionParams(proto.Message): + r"""Description of which voice to use for speech synthesis. + + Attributes: + name (str): + Optional. The name of the voice. If not set, the service + will choose a voice based on the other parameters such as + language_code and + [ssml_gender][google.cloud.dialogflow.v2beta1.VoiceSelectionParams.ssml_gender]. + + For the list of available voices, please refer to `Supported + voices and + languages `__. + ssml_gender (google.cloud.dialogflow_v2beta1.types.SsmlVoiceGender): + Optional. The preferred gender of the voice. If not set, the + service will choose a voice based on the other parameters + such as language_code and + [name][google.cloud.dialogflow.v2beta1.VoiceSelectionParams.name]. + Note that this is only a preference, not requirement. If a + voice of the appropriate gender is not available, the + synthesizer should substitute a voice with a different + gender rather than failing the request. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + ssml_gender = proto.Field( + proto.ENUM, + number=2, + enum='SsmlVoiceGender', + ) + + +class SynthesizeSpeechConfig(proto.Message): + r"""Configuration of how speech should be synthesized. + + Attributes: + speaking_rate (float): + Optional. Speaking rate/speed, in the range [0.25, 4.0]. 1.0 + is the normal native speed supported by the specific voice. + 2.0 is twice as fast, and 0.5 is half as fast. If + unset(0.0), defaults to the native 1.0 speed. Any other + values < 0.25 or > 4.0 will return an error. + pitch (float): + Optional. Speaking pitch, in the range [-20.0, 20.0]. 20 + means increase 20 semitones from the original pitch. -20 + means decrease 20 semitones from the original pitch. + volume_gain_db (float): + Optional. Volume gain (in dB) of the normal native volume + supported by the specific voice, in the range [-96.0, 16.0]. + If unset, or set to a value of 0.0 (dB), will play at normal + native signal amplitude. A value of -6.0 (dB) will play at + approximately half the amplitude of the normal native signal + amplitude. A value of +6.0 (dB) will play at approximately + twice the amplitude of the normal native signal amplitude. + We strongly recommend not to exceed +10 (dB) as there's + usually no effective increase in loudness for any value + greater than that. + effects_profile_id (Sequence[str]): + Optional. An identifier which selects 'audio + effects' profiles that are applied on (post + synthesized) text to speech. Effects are applied + on top of each other in the order they are + given. + voice (google.cloud.dialogflow_v2beta1.types.VoiceSelectionParams): + Optional. The desired voice of the + synthesized audio. + """ + + speaking_rate = proto.Field( + proto.DOUBLE, + number=1, + ) + pitch = proto.Field( + proto.DOUBLE, + number=2, + ) + volume_gain_db = proto.Field( + proto.DOUBLE, + number=3, + ) + effects_profile_id = proto.RepeatedField( + proto.STRING, + number=5, + ) + voice = proto.Field( + proto.MESSAGE, + number=4, + message='VoiceSelectionParams', + ) + + +class OutputAudioConfig(proto.Message): + r"""Instructs the speech synthesizer how to generate the output + audio content. If this audio config is supplied in a request, it + overrides all existing text-to-speech settings applied to the + agent. + + Attributes: + audio_encoding (google.cloud.dialogflow_v2beta1.types.OutputAudioEncoding): + Required. Audio encoding of the synthesized + audio content. + sample_rate_hertz (int): + The synthesis sample rate (in hertz) for this + audio. If not provided, then the synthesizer + will use the default sample rate based on the + audio encoding. If this is different from the + voice's natural sample rate, then the + synthesizer will honor this request by + converting to the desired sample rate (which + might result in worse audio quality). + synthesize_speech_config (google.cloud.dialogflow_v2beta1.types.SynthesizeSpeechConfig): + Configuration of how speech should be + synthesized. + """ + + audio_encoding = proto.Field( + proto.ENUM, + number=1, + enum='OutputAudioEncoding', + ) + sample_rate_hertz = proto.Field( + proto.INT32, + number=2, + ) + synthesize_speech_config = proto.Field( + proto.MESSAGE, + number=3, + message='SynthesizeSpeechConfig', + ) + + +class TelephonyDtmfEvents(proto.Message): + r"""A wrapper of repeated TelephonyDtmf digits. + + Attributes: + dtmf_events (Sequence[google.cloud.dialogflow_v2beta1.types.TelephonyDtmf]): + A sequence of TelephonyDtmf digits. + """ + + dtmf_events = proto.RepeatedField( + proto.ENUM, + number=1, + enum='TelephonyDtmf', + ) + + +class SpeechToTextConfig(proto.Message): + r"""Configures speech transcription for + [ConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfile]. + + Attributes: + speech_model_variant (google.cloud.dialogflow_v2beta1.types.SpeechModelVariant): + The speech model used in speech to text. + ``SPEECH_MODEL_VARIANT_UNSPECIFIED``, ``USE_BEST_AVAILABLE`` + will be treated as ``USE_ENHANCED``. It can be overridden in + [AnalyzeContentRequest][google.cloud.dialogflow.v2beta1.AnalyzeContentRequest] + and + [StreamingAnalyzeContentRequest][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest] + request. If enhanced model variant is specified and an + enhanced version of the specified model for the language + does not exist, then it would emit an error. + """ + + speech_model_variant = proto.Field( + proto.ENUM, + number=1, + enum='SpeechModelVariant', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/context.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/context.py new file mode 100644 index 000000000..a2943b2dd --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/context.py @@ -0,0 +1,327 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2beta1', + manifest={ + 'Context', + 'ListContextsRequest', + 'ListContextsResponse', + 'GetContextRequest', + 'CreateContextRequest', + 'UpdateContextRequest', + 'DeleteContextRequest', + 'DeleteAllContextsRequest', + }, +) + + +class Context(proto.Message): + r"""Dialogflow contexts are similar to natural language context. If a + person says to you "they are orange", you need context in order to + understand what "they" is referring to. Similarly, for Dialogflow to + handle an end-user expression like that, it needs to be provided + with context in order to correctly match an intent. + + Using contexts, you can control the flow of a conversation. You can + configure contexts for an intent by setting input and output + contexts, which are identified by string names. When an intent is + matched, any configured output contexts for that intent become + active. While any contexts are active, Dialogflow is more likely to + match intents that are configured with input contexts that + correspond to the currently active contexts. + + For more information about context, see the `Contexts + guide `__. + + Attributes: + name (str): + Required. The unique identifier of the context. Supported + formats: + + - ``projects//agent/sessions//contexts/``, + - ``projects//locations//agent/sessions//contexts/``, + - ``projects//agent/environments//users//sessions//contexts/``, + - ``projects//locations//agent/environments//users//sessions//contexts/``, + + The ``Context ID`` is always converted to lowercase, may + only contain characters in a-zA-Z0-9_-% and may be at most + 250 bytes long. + + If ``Environment ID`` is not specified, we assume default + 'draft' environment. If ``User ID`` is not specified, we + assume default '-' user. + + The following context names are reserved for internal use by + Dialogflow. You should not use these contexts or create + contexts with these names: + + - ``__system_counters__`` + - ``*_id_dialog_context`` + - ``*_dialog_params_size`` + lifespan_count (int): + Optional. The number of conversational query requests after + which the context expires. The default is ``0``. If set to + ``0``, the context expires immediately. Contexts expire + automatically after 20 minutes if there are no matching + queries. + parameters (google.protobuf.struct_pb2.Struct): + Optional. The collection of parameters + associated with this context. + Depending on your protocol or client library + language, this is a map, associative array, + symbol table, dictionary, or JSON object + composed of a collection of (MapKey, MapValue) + pairs: + - MapKey type: string + - MapKey value: parameter name + - MapValue type: + - If parameter's entity type is a + composite entity: map - Else: depending on + parameter value type, could be one of string, + number, boolean, null, list or map + - MapValue value: + - If parameter's entity type is a + composite entity: map from composite + entity property names to property values - + Else: parameter value + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + lifespan_count = proto.Field( + proto.INT32, + number=2, + ) + parameters = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + + +class ListContextsRequest(proto.Message): + r"""The request message for + [Contexts.ListContexts][google.cloud.dialogflow.v2beta1.Contexts.ListContexts]. + + Attributes: + parent (str): + Required. The session to list all contexts from. Supported + formats: + + - \`projects//agent/sessions/, + - ``projects//locations//agent/sessions/``, + - ``projects//agent/environments//users//sessions/``, + - ``projects//locations//agent/environments//users//sessions/``, + + If ``Location ID`` is not specified we assume default 'us' + location. If ``Environment ID`` is not specified, we assume + default 'draft' environment. If ``User ID`` is not + specified, we assume default '-' user. + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListContextsResponse(proto.Message): + r"""The response message for + [Contexts.ListContexts][google.cloud.dialogflow.v2beta1.Contexts.ListContexts]. + + Attributes: + contexts (Sequence[google.cloud.dialogflow_v2beta1.types.Context]): + The list of contexts. There will be a maximum number of + items returned based on the page_size field in the request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + contexts = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Context', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetContextRequest(proto.Message): + r"""The request message for + [Contexts.GetContext][google.cloud.dialogflow.v2beta1.Contexts.GetContext]. + + Attributes: + name (str): + Required. The name of the context. Supported formats: + + - ``projects//agent/sessions//contexts/``, + - ``projects//locations//agent/sessions//contexts/``, + - ``projects//agent/environments//users//sessions//contexts/``, + - ``projects//locations//agent/environments//users//sessions//contexts/``, + + If ``Location ID`` is not specified we assume default 'us' + location. If ``Environment ID`` is not specified, we assume + default 'draft' environment. If ``User ID`` is not + specified, we assume default '-' user. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateContextRequest(proto.Message): + r"""The request message for + [Contexts.CreateContext][google.cloud.dialogflow.v2beta1.Contexts.CreateContext]. + + Attributes: + parent (str): + Required. The session to create a context for. Supported + formats: + + - \`projects//agent/sessions/, + - ``projects//locations//agent/sessions/``, + - ``projects//agent/environments//users//sessions/``, + - ``projects//locations//agent/environments//users//sessions/``, + + If ``Location ID`` is not specified we assume default 'us' + location. If ``Environment ID`` is not specified, we assume + default 'draft' environment. If ``User ID`` is not + specified, we assume default '-' user. + context (google.cloud.dialogflow_v2beta1.types.Context): + Required. The context to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + context = proto.Field( + proto.MESSAGE, + number=2, + message='Context', + ) + + +class UpdateContextRequest(proto.Message): + r"""The request message for + [Contexts.UpdateContext][google.cloud.dialogflow.v2beta1.Contexts.UpdateContext]. + + Attributes: + context (google.cloud.dialogflow_v2beta1.types.Context): + Required. The context to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which fields + get updated. + """ + + context = proto.Field( + proto.MESSAGE, + number=1, + message='Context', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteContextRequest(proto.Message): + r"""The request message for + [Contexts.DeleteContext][google.cloud.dialogflow.v2beta1.Contexts.DeleteContext]. + + Attributes: + name (str): + Required. The name of the context to delete. Supported + formats: + + - ``projects//agent/sessions//contexts/``, + - ``projects//locations//agent/sessions//contexts/``, + - ``projects//agent/environments//users//sessions//contexts/``, + - ``projects//locations//agent/environments//users//sessions//contexts/``, + + If ``Location ID`` is not specified we assume default 'us' + location. If ``Environment ID`` is not specified, we assume + default 'draft' environment. If ``User ID`` is not + specified, we assume default '-' user. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteAllContextsRequest(proto.Message): + r"""The request message for + [Contexts.DeleteAllContexts][google.cloud.dialogflow.v2beta1.Contexts.DeleteAllContexts]. + + Attributes: + parent (str): + Required. The name of the session to delete all contexts + from. Supported formats: + + - \`projects//agent/sessions/, + - ``projects//locations//agent/sessions/``, + - ``projects//agent/environments//users//sessions/``, + - ``projects//locations//agent/environments//users//sessions/``, + + If ``Location ID`` is not specified we assume default 'us' + location. If ``Environment ID`` is not specified we assume + default 'draft' environment. If ``User ID`` is not + specified, we assume default '-' user. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation.py new file mode 100644 index 000000000..39b5ebd47 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation.py @@ -0,0 +1,462 @@ +# -*- 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.dialogflow_v2beta1.types import participant +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2beta1', + manifest={ + 'Conversation', + 'ConversationPhoneNumber', + 'CreateConversationRequest', + 'ListConversationsRequest', + 'ListConversationsResponse', + 'GetConversationRequest', + 'CompleteConversationRequest', + 'CreateMessageRequest', + 'BatchCreateMessagesRequest', + 'BatchCreateMessagesResponse', + 'ListMessagesRequest', + 'ListMessagesResponse', + }, +) + + +class Conversation(proto.Message): + r"""Represents a conversation. + A conversation is an interaction between an agent, including + live agents and Dialogflow agents, and a support customer. + Conversations can include phone calls and text-based chat + sessions. + + Attributes: + name (str): + Output only. The unique identifier of this conversation. + Format: + ``projects//locations//conversations/``. + lifecycle_state (google.cloud.dialogflow_v2beta1.types.Conversation.LifecycleState): + Output only. The current state of the + Conversation. + conversation_profile (str): + Required. The Conversation Profile to be used to configure + this Conversation. This field cannot be updated. Format: + ``projects//locations//conversationProfiles/``. + phone_number (google.cloud.dialogflow_v2beta1.types.ConversationPhoneNumber): + Output only. Required if the conversation is + to be connected over telephony. + conversation_stage (google.cloud.dialogflow_v2beta1.types.Conversation.ConversationStage): + The stage of a conversation. It indicates whether the + virtual agent or a human agent is handling the conversation. + + If the conversation is created with the conversation profile + that has Dialogflow config set, defaults to + [ConversationStage.VIRTUAL_AGENT_STAGE][google.cloud.dialogflow.v2beta1.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE]; + Otherwise, defaults to + [ConversationStage.HUMAN_ASSIST_STAGE][google.cloud.dialogflow.v2beta1.Conversation.ConversationStage.HUMAN_ASSIST_STAGE]. + + If the conversation is created with the conversation profile + that has Dialogflow config set but explicitly sets + conversation_stage to + [ConversationStage.HUMAN_ASSIST_STAGE][google.cloud.dialogflow.v2beta1.Conversation.ConversationStage.HUMAN_ASSIST_STAGE], + it skips + [ConversationStage.VIRTUAL_AGENT_STAGE][google.cloud.dialogflow.v2beta1.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE] + stage and directly goes to + [ConversationStage.HUMAN_ASSIST_STAGE][google.cloud.dialogflow.v2beta1.Conversation.ConversationStage.HUMAN_ASSIST_STAGE]. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the conversation was + started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the conversation was + finished. + """ + class LifecycleState(proto.Enum): + r"""Enumeration of the completion status of the conversation.""" + LIFECYCLE_STATE_UNSPECIFIED = 0 + IN_PROGRESS = 1 + COMPLETED = 2 + + class ConversationStage(proto.Enum): + r"""Enumeration of the different conversation stages a + conversation can be in. Reference: + https://cloud.google.com/dialogflow/priv/docs/contact- + center/basics#stages + """ + CONVERSATION_STAGE_UNSPECIFIED = 0 + VIRTUAL_AGENT_STAGE = 1 + HUMAN_ASSIST_STAGE = 2 + + name = proto.Field( + proto.STRING, + number=1, + ) + lifecycle_state = proto.Field( + proto.ENUM, + number=2, + enum=LifecycleState, + ) + conversation_profile = proto.Field( + proto.STRING, + number=3, + ) + phone_number = proto.Field( + proto.MESSAGE, + number=4, + message='ConversationPhoneNumber', + ) + conversation_stage = proto.Field( + proto.ENUM, + number=7, + enum=ConversationStage, + ) + start_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + +class ConversationPhoneNumber(proto.Message): + r"""Represents a phone number for telephony integration. It + allows for connecting a particular conversation over telephony. + + Attributes: + phone_number (str): + Output only. The phone number to connect to + this conversation. + """ + + phone_number = proto.Field( + proto.STRING, + number=3, + ) + + +class CreateConversationRequest(proto.Message): + r"""The request message for + [Conversations.CreateConversation][google.cloud.dialogflow.v2beta1.Conversations.CreateConversation]. + + Attributes: + parent (str): + Required. Resource identifier of the project creating the + conversation. Format: + ``projects//locations/``. + conversation (google.cloud.dialogflow_v2beta1.types.Conversation): + Required. The conversation to create. + conversation_id (str): + Optional. Identifier of the conversation. Generally it's + auto generated by Google. Only set it if you cannot wait for + the response to return a auto-generated one to you. + + The conversation ID must be compliant with the regression + fomula "[a-zA-Z][a-zA-Z0-9_-]*" with the characters length + in range of [3,64]. If the field is provided, the caller is + resposible for + + 1. the uniqueness of the ID, otherwise the request will be + rejected. + 2. the consistency for whether to use custom ID or not under + a project to better ensure uniqueness. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + conversation = proto.Field( + proto.MESSAGE, + number=2, + message='Conversation', + ) + conversation_id = proto.Field( + proto.STRING, + number=3, + ) + + +class ListConversationsRequest(proto.Message): + r"""The request message for + [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. + + Attributes: + parent (str): + Required. The project from which to list all conversation. + Format: ``projects//locations/``. + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + filter (str): + A filter expression that filters conversations listed in the + response. In general, the expression must specify the field + name, a comparison operator, and the value to use for + filtering: + + .. raw:: html + +
    +
  • The value must be a string, a number, or a boolean.
  • +
  • The comparison operator must be either `=`,`!=`, `>`, or `<`.
  • +
  • To filter on multiple expressions, separate the + expressions with `AND` or `OR` (omitting both implies `AND`).
  • +
  • For clarity, expressions can be enclosed in parentheses.
  • +
+ Only `lifecycle_state` can be filtered on in this way. For example, + the following expression only returns `COMPLETED` conversations: + + ``lifecycle_state = "COMPLETED"`` + + For more information about filtering, see `API + Filtering `__. + """ + + 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 ListConversationsResponse(proto.Message): + r"""The response message for + [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. + + Attributes: + conversations (Sequence[google.cloud.dialogflow_v2beta1.types.Conversation]): + The list of conversations. There will be a maximum number of + items returned based on the page_size field in the request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + conversations = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Conversation', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetConversationRequest(proto.Message): + r"""The request message for + [Conversations.GetConversation][google.cloud.dialogflow.v2beta1.Conversations.GetConversation]. + + Attributes: + name (str): + Required. The name of the conversation. Format: + ``projects//locations//conversations/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CompleteConversationRequest(proto.Message): + r"""The request message for + [Conversations.CompleteConversation][google.cloud.dialogflow.v2beta1.Conversations.CompleteConversation]. + + Attributes: + name (str): + Required. Resource identifier of the conversation to close. + Format: + ``projects//locations//conversations/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateMessageRequest(proto.Message): + r"""The request message to create one Message. Currently it is + only used in BatchCreateMessagesRequest. + + Attributes: + parent (str): + Required. Resource identifier of the conversation to create + message. Format: + ``projects//locations//conversations/``. + message (google.cloud.dialogflow_v2beta1.types.Message): + Required. The message to create. + [Message.participant][google.cloud.dialogflow.v2beta1.Message.participant] + is required. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + message = proto.Field( + proto.MESSAGE, + number=2, + message=participant.Message, + ) + + +class BatchCreateMessagesRequest(proto.Message): + r"""The request message for + [Conversations.BatchCreateMessagesRequest][]. + + Attributes: + parent (str): + Required. Resource identifier of the conversation to create + message. Format: + ``projects//locations//conversations/``. + requests (Sequence[google.cloud.dialogflow_v2beta1.types.CreateMessageRequest]): + Required. A maximum of 1000 Messages can be created in a + batch. [CreateMessageRequest.message.send_time][] is + required. All created messages will have identical + [Message.create_time][google.cloud.dialogflow.v2beta1.Message.create_time]. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + requests = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='CreateMessageRequest', + ) + + +class BatchCreateMessagesResponse(proto.Message): + r"""The request message for + [Conversations.BatchCreateMessagesResponse][]. + + Attributes: + messages (Sequence[google.cloud.dialogflow_v2beta1.types.Message]): + Messages created. + """ + + messages = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=participant.Message, + ) + + +class ListMessagesRequest(proto.Message): + r"""The request message for + [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. + + Attributes: + parent (str): + Required. The name of the conversation to list messages for. + Format: + ``projects//locations//conversations/`` + filter (str): + Optional. Filter on message fields. Currently predicates on + ``create_time`` and ``create_time_epoch_microseconds`` are + supported. ``create_time`` only support milliseconds + accuracy. E.g., + ``create_time_epoch_microseconds > 1551790877964485`` or + ``create_time > "2017-01-15T01:30:15.01Z"``. + + For more information about filtering, see `API + Filtering `__. + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListMessagesResponse(proto.Message): + r"""The response message for + [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. + + Attributes: + messages (Sequence[google.cloud.dialogflow_v2beta1.types.Message]): + Required. The list of messages. There will be a maximum + number of items returned based on the page_size field in the + request. ``messages`` is sorted by ``create_time`` in + descending order. + next_page_token (str): + Optional. Token to retrieve the next page of + results, or empty if there are no more results + in the list. + """ + + @property + def raw_page(self): + return self + + messages = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=participant.Message, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation_event.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation_event.py new file mode 100644 index 000000000..9d13c896d --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation_event.py @@ -0,0 +1,83 @@ +# -*- 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.dialogflow_v2beta1.types import participant +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2beta1', + manifest={ + 'ConversationEvent', + }, +) + + +class ConversationEvent(proto.Message): + r"""Represents a notification sent to Pub/Sub subscribers for + conversation lifecycle events. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + conversation (str): + Required. The unique identifier of the conversation this + notification refers to. Format: + ``projects//conversations/``. + type_ (google.cloud.dialogflow_v2beta1.types.ConversationEvent.Type): + Required. The type of the event that this + notification refers to. + error_status (google.rpc.status_pb2.Status): + Optional. More detailed information about an error. Only set + for type UNRECOVERABLE_ERROR_IN_PHONE_CALL. + new_message_payload (google.cloud.dialogflow_v2beta1.types.Message): + Payload of NEW_MESSAGE event. + + This field is a member of `oneof`_ ``payload``. + """ + class Type(proto.Enum): + r"""Enumeration of the types of events available.""" + TYPE_UNSPECIFIED = 0 + CONVERSATION_STARTED = 1 + CONVERSATION_FINISHED = 2 + NEW_MESSAGE = 5 + UNRECOVERABLE_ERROR = 4 + + conversation = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.ENUM, + number=2, + enum=Type, + ) + error_status = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + new_message_payload = proto.Field( + proto.MESSAGE, + number=4, + oneof='payload', + message=participant.Message, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation_profile.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation_profile.py new file mode 100644 index 000000000..359d6785d --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation_profile.py @@ -0,0 +1,869 @@ +# -*- 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.dialogflow_v2beta1.types import audio_config +from google.cloud.dialogflow_v2beta1.types import participant +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2beta1', + manifest={ + 'ConversationProfile', + 'AutomatedAgentConfig', + 'HumanAgentAssistantConfig', + 'HumanAgentHandoffConfig', + 'NotificationConfig', + 'LoggingConfig', + 'ListConversationProfilesRequest', + 'ListConversationProfilesResponse', + 'GetConversationProfileRequest', + 'CreateConversationProfileRequest', + 'UpdateConversationProfileRequest', + 'DeleteConversationProfileRequest', + }, +) + + +class ConversationProfile(proto.Message): + r"""Defines the services to connect to incoming Dialogflow + conversations. + + Attributes: + name (str): + The unique identifier of this conversation profile. Format: + ``projects//locations//conversationProfiles/``. + display_name (str): + Required. Human readable name for this + profile. Max length 1024 bytes. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Create time of the conversation + profile. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Update time of the conversation + profile. + automated_agent_config (google.cloud.dialogflow_v2beta1.types.AutomatedAgentConfig): + Configuration for an automated agent to use + with this profile. + human_agent_assistant_config (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig): + Configuration for agent assistance to use + with this profile. + human_agent_handoff_config (google.cloud.dialogflow_v2beta1.types.HumanAgentHandoffConfig): + Configuration for connecting to a live agent. + Currently, this feature is not general + available, please contact Google to get access. + notification_config (google.cloud.dialogflow_v2beta1.types.NotificationConfig): + Configuration for publishing conversation + lifecycle events. + logging_config (google.cloud.dialogflow_v2beta1.types.LoggingConfig): + Configuration for logging conversation + lifecycle events. + new_message_event_notification_config (google.cloud.dialogflow_v2beta1.types.NotificationConfig): + Configuration for publishing new message events. Event will + be sent in format of + [ConversationEvent][google.cloud.dialogflow.v2beta1.ConversationEvent] + stt_config (google.cloud.dialogflow_v2beta1.types.SpeechToTextConfig): + Settings for speech transcription. + language_code (str): + Language code for the conversation profile. If not + specified, the language is en-US. Language at + ConversationProfile should be set for all non en-us + languages. This should be a + `BCP-47 `__ + language tag. Example: "en-US". + time_zone (str): + The time zone of this conversational profile from the `time + zone database `__, e.g., + America/New_York, Europe/Paris. Defaults to + America/New_York. + security_settings (str): + Name of the CX SecuritySettings reference for the agent. + Format: + ``projects//locations//securitySettings/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + create_time = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=12, + message=timestamp_pb2.Timestamp, + ) + automated_agent_config = proto.Field( + proto.MESSAGE, + number=3, + message='AutomatedAgentConfig', + ) + human_agent_assistant_config = proto.Field( + proto.MESSAGE, + number=4, + message='HumanAgentAssistantConfig', + ) + human_agent_handoff_config = proto.Field( + proto.MESSAGE, + number=5, + message='HumanAgentHandoffConfig', + ) + notification_config = proto.Field( + proto.MESSAGE, + number=6, + message='NotificationConfig', + ) + logging_config = proto.Field( + proto.MESSAGE, + number=7, + message='LoggingConfig', + ) + new_message_event_notification_config = proto.Field( + proto.MESSAGE, + number=8, + message='NotificationConfig', + ) + stt_config = proto.Field( + proto.MESSAGE, + number=9, + message=audio_config.SpeechToTextConfig, + ) + language_code = proto.Field( + proto.STRING, + number=10, + ) + time_zone = proto.Field( + proto.STRING, + number=14, + ) + security_settings = proto.Field( + proto.STRING, + number=13, + ) + + +class AutomatedAgentConfig(proto.Message): + r"""Defines the Automated Agent to connect to a conversation. + + Attributes: + agent (str): + Required. ID of the Dialogflow agent environment to use. + + This project needs to either be the same project as the + conversation or you need to grant + ``service-@gcp-sa-dialogflow.iam.gserviceaccount.com`` + the ``Dialogflow API Service Agent`` role in this project. + + - For ES agents, use format: + ``projects//locations//agent/environments/``. + If environment is not specified, the default ``draft`` + environment is used. Refer to + `DetectIntentRequest `__ + for more details. + + - For CX agents, use format + ``projects//locations//agents//environments/``. + If environment is not specified, the default ``draft`` + environment is used. + """ + + agent = proto.Field( + proto.STRING, + number=1, + ) + + +class HumanAgentAssistantConfig(proto.Message): + r"""Defines the Human Agent Assistant to connect to a + conversation. + + Attributes: + notification_config (google.cloud.dialogflow_v2beta1.types.NotificationConfig): + Pub/Sub topic on which to publish new agent + assistant events. + human_agent_suggestion_config (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionConfig): + Configuration for agent assistance of human + agent participant. + end_user_suggestion_config (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionConfig): + Configuration for agent assistance of end + user participant. + Currently, this feature is not general + available, please contact Google to get access. + message_analysis_config (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.MessageAnalysisConfig): + Configuration for message analysis. + """ + + class SuggestionTriggerSettings(proto.Message): + r"""Settings of suggestion trigger. + + Attributes: + no_small_talk (bool): + Do not trigger if last utterance is small + talk. + only_end_user (bool): + Only trigger suggestion if participant role of last + utterance is END_USER. + """ + + no_small_talk = proto.Field( + proto.BOOL, + number=1, + ) + only_end_user = proto.Field( + proto.BOOL, + number=2, + ) + + class SuggestionFeatureConfig(proto.Message): + r"""Config for suggestion features. + + Attributes: + suggestion_feature (google.cloud.dialogflow_v2beta1.types.SuggestionFeature): + The suggestion feature. + enable_event_based_suggestion (bool): + Automatically iterates all participants and tries to compile + suggestions. + + Supported features: ARTICLE_SUGGESTION, FAQ, + DIALOGFLOW_ASSIST. + suggestion_trigger_settings (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionTriggerSettings): + Settings of suggestion trigger. + + Currently, only ARTICLE_SUGGESTION, FAQ, and + DIALOGFLOW_ASSIST will use this field. + query_config (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionQueryConfig): + Configs of query. + conversation_model_config (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.ConversationModelConfig): + Configs of custom conversation model. + """ + + suggestion_feature = proto.Field( + proto.MESSAGE, + number=5, + message=participant.SuggestionFeature, + ) + enable_event_based_suggestion = proto.Field( + proto.BOOL, + number=3, + ) + suggestion_trigger_settings = proto.Field( + proto.MESSAGE, + number=10, + message='HumanAgentAssistantConfig.SuggestionTriggerSettings', + ) + query_config = proto.Field( + proto.MESSAGE, + number=6, + message='HumanAgentAssistantConfig.SuggestionQueryConfig', + ) + conversation_model_config = proto.Field( + proto.MESSAGE, + number=7, + message='HumanAgentAssistantConfig.ConversationModelConfig', + ) + + class SuggestionConfig(proto.Message): + r"""Detail human agent assistant config. + + Attributes: + feature_configs (Sequence[google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionFeatureConfig]): + Configuration of different suggestion + features. One feature can have only one config. + group_suggestion_responses (bool): + If ``group_suggestion_responses`` is false, and there are + multiple ``feature_configs`` in ``event based suggestion`` + or StreamingAnalyzeContent, we will try to deliver + suggestions to customers as soon as we get new suggestion. + Different type of suggestions based on the same context will + be in separate Pub/Sub event or + ``StreamingAnalyzeContentResponse``. + + If ``group_suggestion_responses`` set to true. All the + suggestions to the same participant based on the same + context will be grouped into a single Pub/Sub event or + StreamingAnalyzeContentResponse. + """ + + feature_configs = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='HumanAgentAssistantConfig.SuggestionFeatureConfig', + ) + group_suggestion_responses = proto.Field( + proto.BOOL, + number=3, + ) + + class SuggestionQueryConfig(proto.Message): + r"""Config for suggestion query. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + knowledge_base_query_source (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionQueryConfig.KnowledgeBaseQuerySource): + Query from knowledgebase. It is used by: ARTICLE_SUGGESTION, + FAQ. + + This field is a member of `oneof`_ ``query_source``. + document_query_source (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionQueryConfig.DocumentQuerySource): + Query from knowledge base document. It is used by: + SMART_REPLY, SMART_COMPOSE. + + This field is a member of `oneof`_ ``query_source``. + dialogflow_query_source (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionQueryConfig.DialogflowQuerySource): + Query from Dialogflow agent. It is used by + DIALOGFLOW_ASSIST. + + This field is a member of `oneof`_ ``query_source``. + max_results (int): + Maximum number of results to return. + Currently, if unset, defaults to 10. And the max + number is 20. + confidence_threshold (float): + Confidence threshold of query result. + + Agent Assist gives each suggestion a score in the range + [0.0, 1.0], based on the relevance between the suggestion + and the current conversation context. A score of 0.0 has no + relevance, while a score of 1.0 has high relevance. Only + suggestions with a score greater than or equal to the value + of this field are included in the results. + + For a baseline model (the default), the recommended value is + in the range [0.05, 0.1]. + + For a custom model, there is no recommended value. Tune this + value by starting from a very low value and slowly + increasing until you have desired results. + + If this field is not set, it is default to 0.0, which means + that all suggestions are returned. + + Supported features: ARTICLE_SUGGESTION, FAQ, SMART_REPLY, + SMART_COMPOSE. + context_filter_settings (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionQueryConfig.ContextFilterSettings): + Determines how recent conversation context is + filtered when generating suggestions. If + unspecified, no messages will be dropped. + """ + + class KnowledgeBaseQuerySource(proto.Message): + r"""Knowledge base source settings. + + Supported features: ARTICLE_SUGGESTION, FAQ. + + Attributes: + knowledge_bases (Sequence[str]): + Required. Knowledge bases to query. Format: + ``projects//locations//knowledgeBases/``. + Currently, only one knowledge base is supported. + """ + + knowledge_bases = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class DocumentQuerySource(proto.Message): + r"""Document source settings. + + Supported features: SMART_REPLY, SMART_COMPOSE. + + Attributes: + documents (Sequence[str]): + Required. Knowledge documents to query from. Format: + ``projects//locations//knowledgeBases//documents/``. + Currently, only one document is supported. + """ + + documents = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class DialogflowQuerySource(proto.Message): + r"""Dialogflow source setting. + + Supported feature: DIALOGFLOW_ASSIST. + + Attributes: + agent (str): + Required. The name of a dialogflow virtual agent used for + end user side intent detection and suggestion. Format: + ``projects//locations//agent``. + When multiple agents are allowed in the same Dialogflow + project. + """ + + agent = proto.Field( + proto.STRING, + number=1, + ) + + class ContextFilterSettings(proto.Message): + r"""Settings that determine how to filter recent conversation + context when generating suggestions. + + Attributes: + drop_handoff_messages (bool): + If set to true, the last message from virtual + agent (hand off message) and the message before + it (trigger message of hand off) are dropped. + drop_virtual_agent_messages (bool): + If set to true, all messages from virtual + agent are dropped. + drop_ivr_messages (bool): + If set to true, all messages from ivr stage + are dropped. + """ + + drop_handoff_messages = proto.Field( + proto.BOOL, + number=1, + ) + drop_virtual_agent_messages = proto.Field( + proto.BOOL, + number=2, + ) + drop_ivr_messages = proto.Field( + proto.BOOL, + number=3, + ) + + knowledge_base_query_source = proto.Field( + proto.MESSAGE, + number=1, + oneof='query_source', + message='HumanAgentAssistantConfig.SuggestionQueryConfig.KnowledgeBaseQuerySource', + ) + document_query_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='query_source', + message='HumanAgentAssistantConfig.SuggestionQueryConfig.DocumentQuerySource', + ) + dialogflow_query_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='query_source', + message='HumanAgentAssistantConfig.SuggestionQueryConfig.DialogflowQuerySource', + ) + max_results = proto.Field( + proto.INT32, + number=4, + ) + confidence_threshold = proto.Field( + proto.FLOAT, + number=5, + ) + context_filter_settings = proto.Field( + proto.MESSAGE, + number=7, + message='HumanAgentAssistantConfig.SuggestionQueryConfig.ContextFilterSettings', + ) + + class ConversationModelConfig(proto.Message): + r"""Custom conversation models used in agent assist feature. + + Supported feature: ARTICLE_SUGGESTION, SMART_COMPOSE, SMART_REPLY. + + Attributes: + model (str): + Conversation model resource name. Format: + ``projects//conversationModels/``. + """ + + model = proto.Field( + proto.STRING, + number=1, + ) + + class MessageAnalysisConfig(proto.Message): + r"""Configuration for analyses to run on each conversation + message. + + Attributes: + enable_entity_extraction (bool): + Enable entity extraction in conversation messages on `agent + assist + stage `__. + If unspecified, defaults to false. + + Currently, this feature is not general available, please + contact Google to get access. + enable_sentiment_analysis (bool): + Enable sentiment analysis in conversation messages on `agent + assist + stage `__. + If unspecified, defaults to false. Sentiment analysis + inspects user input and identifies the prevailing subjective + opinion, especially to determine a user's attitude as + positive, negative, or neutral: + https://cloud.google.com/natural-language/docs/basics#sentiment_analysis + For + [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.StreamingAnalyzeContent] + method, result will be in + [StreamingAnalyzeContentResponse.message.SentimentAnalysisResult][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentResponse.message]. + For + [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent] + method, result will be in + [AnalyzeContentResponse.message.SentimentAnalysisResult][google.cloud.dialogflow.v2beta1.AnalyzeContentResponse.message] + For + [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages] + method, result will be in + [ListMessagesResponse.messages.SentimentAnalysisResult][google.cloud.dialogflow.v2beta1.ListMessagesResponse.messages] + If Pub/Sub notification is configured, result will be in + [ConversationEvent.new_message_payload.SentimentAnalysisResult][google.cloud.dialogflow.v2beta1.ConversationEvent.new_message_payload]. + """ + + enable_entity_extraction = proto.Field( + proto.BOOL, + number=2, + ) + enable_sentiment_analysis = proto.Field( + proto.BOOL, + number=3, + ) + + notification_config = proto.Field( + proto.MESSAGE, + number=2, + message='NotificationConfig', + ) + human_agent_suggestion_config = proto.Field( + proto.MESSAGE, + number=3, + message=SuggestionConfig, + ) + end_user_suggestion_config = proto.Field( + proto.MESSAGE, + number=4, + message=SuggestionConfig, + ) + message_analysis_config = proto.Field( + proto.MESSAGE, + number=5, + message=MessageAnalysisConfig, + ) + + +class HumanAgentHandoffConfig(proto.Message): + r"""Defines the hand off to a live agent, typically on which + external agent service provider to connect to a conversation. + Currently, this feature is not general available, please contact + Google to get access. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + live_person_config (google.cloud.dialogflow_v2beta1.types.HumanAgentHandoffConfig.LivePersonConfig): + Uses LivePerson (https://www.liveperson.com). + + This field is a member of `oneof`_ ``agent_service``. + salesforce_live_agent_config (google.cloud.dialogflow_v2beta1.types.HumanAgentHandoffConfig.SalesforceLiveAgentConfig): + Uses Salesforce Live Agent. + + This field is a member of `oneof`_ ``agent_service``. + """ + + class LivePersonConfig(proto.Message): + r"""Configuration specific to LivePerson + (https://www.liveperson.com). + + Attributes: + account_number (str): + Required. Account number of the LivePerson + account to connect. This is the account number + you input at the login page. + """ + + account_number = proto.Field( + proto.STRING, + number=1, + ) + + class SalesforceLiveAgentConfig(proto.Message): + r"""Configuration specific to Salesforce Live Agent. + + Attributes: + organization_id (str): + Required. The organization ID of the + Salesforce account. + deployment_id (str): + Required. Live Agent deployment ID. + button_id (str): + Required. Live Agent chat button ID. + endpoint_domain (str): + Required. Domain of the Live Agent endpoint for this agent. + You can find the endpoint URL in the ``Live Agent settings`` + page. For example if URL has the form + https://d.la4-c2-phx.salesforceliveagent.com/..., you should + fill in d.la4-c2-phx.salesforceliveagent.com. + """ + + organization_id = proto.Field( + proto.STRING, + number=1, + ) + deployment_id = proto.Field( + proto.STRING, + number=2, + ) + button_id = proto.Field( + proto.STRING, + number=3, + ) + endpoint_domain = proto.Field( + proto.STRING, + number=4, + ) + + live_person_config = proto.Field( + proto.MESSAGE, + number=1, + oneof='agent_service', + message=LivePersonConfig, + ) + salesforce_live_agent_config = proto.Field( + proto.MESSAGE, + number=2, + oneof='agent_service', + message=SalesforceLiveAgentConfig, + ) + + +class NotificationConfig(proto.Message): + r"""Defines notification behavior. + + Attributes: + topic (str): + Name of the Pub/Sub topic to publish conversation events + like + [CONVERSATION_STARTED][google.cloud.dialogflow.v2beta1.ConversationEvent.Type.CONVERSATION_STARTED] + as serialized + [ConversationEvent][google.cloud.dialogflow.v2beta1.ConversationEvent] + protos. + + Notification works for phone calls, if this topic either is + in the same project as the conversation or you grant + ``service-@gcp-sa-dialogflow.iam.gserviceaccount.com`` + the ``Dialogflow Service Agent`` role in the topic project. + + Format: + ``projects//locations//topics/``. + message_format (google.cloud.dialogflow_v2beta1.types.NotificationConfig.MessageFormat): + Format of message. + """ + class MessageFormat(proto.Enum): + r"""Format of cloud pub/sub message.""" + MESSAGE_FORMAT_UNSPECIFIED = 0 + PROTO = 1 + JSON = 2 + + topic = proto.Field( + proto.STRING, + number=1, + ) + message_format = proto.Field( + proto.ENUM, + number=2, + enum=MessageFormat, + ) + + +class LoggingConfig(proto.Message): + r"""Defines logging behavior for conversation lifecycle events. + + Attributes: + enable_stackdriver_logging (bool): + Whether to log conversation events like + [CONVERSATION_STARTED][google.cloud.dialogflow.v2beta1.ConversationEvent.Type.CONVERSATION_STARTED] + to Stackdriver in the conversation project as JSON format + [ConversationEvent][google.cloud.dialogflow.v2beta1.ConversationEvent] + protos. + """ + + enable_stackdriver_logging = proto.Field( + proto.BOOL, + number=3, + ) + + +class ListConversationProfilesRequest(proto.Message): + r"""The request message for + [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2beta1.ConversationProfiles.ListConversationProfiles]. + + Attributes: + parent (str): + Required. The project to list all conversation profiles + from. Format: + ``projects//locations/``. + page_size (int): + The maximum number of items to return in a + single page. By default 100 and at most 1000. + page_token (str): + The next_page_token value returned from a previous list + request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListConversationProfilesResponse(proto.Message): + r"""The response message for + [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2beta1.ConversationProfiles.ListConversationProfiles]. + + Attributes: + conversation_profiles (Sequence[google.cloud.dialogflow_v2beta1.types.ConversationProfile]): + The list of project conversation profiles. There is a + maximum number of items returned based on the page_size + field in the request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + conversation_profiles = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ConversationProfile', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetConversationProfileRequest(proto.Message): + r"""The request message for + [ConversationProfiles.GetConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.GetConversationProfile]. + + Attributes: + name (str): + Required. The resource name of the conversation profile. + Format: + ``projects//locations//conversationProfiles/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateConversationProfileRequest(proto.Message): + r"""The request message for + [ConversationProfiles.CreateConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.CreateConversationProfile]. + + Attributes: + parent (str): + Required. The project to create a conversation profile for. + Format: ``projects//locations/``. + conversation_profile (google.cloud.dialogflow_v2beta1.types.ConversationProfile): + Required. The conversation profile to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + conversation_profile = proto.Field( + proto.MESSAGE, + number=2, + message='ConversationProfile', + ) + + +class UpdateConversationProfileRequest(proto.Message): + r"""The request message for + [ConversationProfiles.UpdateConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.UpdateConversationProfile]. + + Attributes: + conversation_profile (google.cloud.dialogflow_v2beta1.types.ConversationProfile): + Required. The conversation profile to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields to + update. + """ + + conversation_profile = proto.Field( + proto.MESSAGE, + number=1, + message='ConversationProfile', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteConversationProfileRequest(proto.Message): + r"""The request message for + [ConversationProfiles.DeleteConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.DeleteConversationProfile]. + + This operation fails if the conversation profile is still referenced + from a phone number. + + Attributes: + name (str): + Required. The name of the conversation profile to delete. + Format: + ``projects//locations//conversationProfiles/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/document.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/document.py new file mode 100644 index 000000000..66c5a74e9 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/document.py @@ -0,0 +1,557 @@ +# -*- 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.dialogflow_v2beta1.types import gcs +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2beta1', + manifest={ + 'Document', + 'GetDocumentRequest', + 'ListDocumentsRequest', + 'ListDocumentsResponse', + 'CreateDocumentRequest', + 'ImportDocumentsRequest', + 'ImportDocumentTemplate', + 'ImportDocumentsResponse', + 'DeleteDocumentRequest', + 'UpdateDocumentRequest', + 'KnowledgeOperationMetadata', + 'ReloadDocumentRequest', + }, +) + + +class Document(proto.Message): + r"""A knowledge document to be used by a + [KnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBase]. + + For more information, see the `knowledge base + guide `__. + + Note: The ``projects.agent.knowledgeBases.documents`` resource is + deprecated; only use ``projects.knowledgeBases.documents``. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Optional. The document resource name. The name must be empty + when creating a document. Format: + ``projects//locations//knowledgeBases//documents/``. + display_name (str): + Required. The display name of the document. + The name must be 1024 bytes or less; otherwise, + the creation request fails. + mime_type (str): + Required. The MIME type of this document. + knowledge_types (Sequence[google.cloud.dialogflow_v2beta1.types.Document.KnowledgeType]): + Required. The knowledge type of document + content. + content_uri (str): + The URI where the file content is located. + + For documents stored in Google Cloud Storage, these URIs + must have the form ``gs:///``. + + NOTE: External URLs must correspond to public webpages, + i.e., they must be indexed by Google Search. In particular, + URLs for showing documents in Google Cloud Storage (i.e. the + URL in your browser) are not supported. Instead use the + ``gs://`` format URI described above. + + This field is a member of `oneof`_ ``source``. + content (str): + The raw content of the document. This field is only + permitted for EXTRACTIVE_QA and FAQ knowledge types. Note: + This field is in the process of being deprecated, please use + raw_content instead. + + This field is a member of `oneof`_ ``source``. + raw_content (bytes): + The raw content of the document. This field is only + permitted for EXTRACTIVE_QA and FAQ knowledge types. + + This field is a member of `oneof`_ ``source``. + enable_auto_reload (bool): + Optional. If true, we try to automatically reload the + document every day (at a time picked by the system). If + false or unspecified, we don't try to automatically reload + the document. + + Currently you can only enable automatic reload for documents + sourced from a public url, see ``source`` field for the + source types. + + Reload status can be tracked in ``latest_reload_status``. If + a reload fails, we will keep the document unchanged. + + If a reload fails with internal errors, the system will try + to reload the document on the next day. If a reload fails + with non-retriable errors (e.g. PERMISION_DENIED), the + system will not try to reload the document anymore. You need + to manually reload the document successfully by calling + ``ReloadDocument`` and clear the errors. + latest_reload_status (google.cloud.dialogflow_v2beta1.types.Document.ReloadStatus): + Output only. The time and status of the + latest reload. This reload may have been + triggered automatically or manually and may not + have succeeded. + metadata (Sequence[google.cloud.dialogflow_v2beta1.types.Document.MetadataEntry]): + Optional. Metadata for the document. The metadata supports + arbitrary key-value pairs. Suggested use cases include + storing a document's title, an external URL distinct from + the document's content_uri, etc. The max size of a ``key`` + or a ``value`` of the metadata is 1024 bytes. + """ + class KnowledgeType(proto.Enum): + r"""The knowledge type of document content.""" + KNOWLEDGE_TYPE_UNSPECIFIED = 0 + FAQ = 1 + EXTRACTIVE_QA = 2 + ARTICLE_SUGGESTION = 3 + SMART_REPLY = 4 + + class ReloadStatus(proto.Message): + r"""The status of a reload attempt. + + Attributes: + time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time of a reload attempt. + This reload may have been triggered + automatically or manually and may not have + succeeded. + status (google.rpc.status_pb2.Status): + Output only. The status of a reload attempt + or the initial load. + """ + + time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + mime_type = proto.Field( + proto.STRING, + number=3, + ) + knowledge_types = proto.RepeatedField( + proto.ENUM, + number=4, + enum=KnowledgeType, + ) + content_uri = proto.Field( + proto.STRING, + number=5, + oneof='source', + ) + content = proto.Field( + proto.STRING, + number=6, + oneof='source', + ) + raw_content = proto.Field( + proto.BYTES, + number=9, + oneof='source', + ) + enable_auto_reload = proto.Field( + proto.BOOL, + number=11, + ) + latest_reload_status = proto.Field( + proto.MESSAGE, + number=12, + message=ReloadStatus, + ) + metadata = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + + +class GetDocumentRequest(proto.Message): + r"""Request message for + [Documents.GetDocument][google.cloud.dialogflow.v2beta1.Documents.GetDocument]. + + Attributes: + name (str): + Required. The name of the document to retrieve. Format + ``projects//locations//knowledgeBases//documents/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListDocumentsRequest(proto.Message): + r"""Request message for + [Documents.ListDocuments][google.cloud.dialogflow.v2beta1.Documents.ListDocuments]. + + Attributes: + parent (str): + Required. The knowledge base to list all documents for. + Format: + ``projects//locations//knowledgeBases/``. + page_size (int): + The maximum number of items to return in a + single page. By default 10 and at most 100. + page_token (str): + The next_page_token value returned from a previous list + request. + filter (str): + The filter expression used to filter documents returned by + the list method. The expression has the following syntax: + + [AND ] ... + + The following fields and operators are supported: + + - knowledge_types with has(:) operator + - display_name with has(:) operator + - state with equals(=) operator + + Examples: + + - "knowledge_types:FAQ" matches documents with FAQ + knowledge type. + - "display_name:customer" matches documents whose display + name contains "customer". + - "state=ACTIVE" matches documents with ACTIVE state. + - "knowledge_types:FAQ AND state=ACTIVE" matches all active + FAQ documents. + + For more information about filtering, see `API + Filtering `__. + """ + + 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 ListDocumentsResponse(proto.Message): + r"""Response message for + [Documents.ListDocuments][google.cloud.dialogflow.v2beta1.Documents.ListDocuments]. + + Attributes: + documents (Sequence[google.cloud.dialogflow_v2beta1.types.Document]): + The list of documents. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + documents = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Document', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateDocumentRequest(proto.Message): + r"""Request message for + [Documents.CreateDocument][google.cloud.dialogflow.v2beta1.Documents.CreateDocument]. + + Attributes: + parent (str): + Required. The knowledge base to create a document for. + Format: + ``projects//locations//knowledgeBases/``. + document (google.cloud.dialogflow_v2beta1.types.Document): + Required. The document to create. + import_gcs_custom_metadata (bool): + Whether to import custom metadata from Google + Cloud Storage. Only valid when the document + source is Google Cloud Storage URI. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + document = proto.Field( + proto.MESSAGE, + number=2, + message='Document', + ) + import_gcs_custom_metadata = proto.Field( + proto.BOOL, + number=3, + ) + + +class ImportDocumentsRequest(proto.Message): + r"""Request message for + [Documents.ImportDocuments][google.cloud.dialogflow.v2beta1.Documents.ImportDocuments]. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The knowledge base to import documents into. + Format: + ``projects//locations//knowledgeBases/``. + gcs_source (google.cloud.dialogflow_v2beta1.types.GcsSources): + The Google Cloud Storage location for the documents. The + path can include a wildcard. + + These URIs may have the forms + ``gs:///``. + ``gs:////*.``. + + This field is a member of `oneof`_ ``source``. + document_template (google.cloud.dialogflow_v2beta1.types.ImportDocumentTemplate): + Required. Document template used for + importing all the documents. + import_gcs_custom_metadata (bool): + Whether to import custom metadata from Google + Cloud Storage. Only valid when the document + source is Google Cloud Storage URI. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + gcs_source = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message=gcs.GcsSources, + ) + document_template = proto.Field( + proto.MESSAGE, + number=3, + message='ImportDocumentTemplate', + ) + import_gcs_custom_metadata = proto.Field( + proto.BOOL, + number=4, + ) + + +class ImportDocumentTemplate(proto.Message): + r"""The template used for importing documents. + + Attributes: + mime_type (str): + Required. The MIME type of the document. + knowledge_types (Sequence[google.cloud.dialogflow_v2beta1.types.Document.KnowledgeType]): + Required. The knowledge type of document + content. + metadata (Sequence[google.cloud.dialogflow_v2beta1.types.ImportDocumentTemplate.MetadataEntry]): + Metadata for the document. The metadata supports arbitrary + key-value pairs. Suggested use cases include storing a + document's title, an external URL distinct from the + document's content_uri, etc. The max size of a ``key`` or a + ``value`` of the metadata is 1024 bytes. + """ + + mime_type = proto.Field( + proto.STRING, + number=1, + ) + knowledge_types = proto.RepeatedField( + proto.ENUM, + number=2, + enum='Document.KnowledgeType', + ) + metadata = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + + +class ImportDocumentsResponse(proto.Message): + r"""Response message for + [Documents.ImportDocuments][google.cloud.dialogflow.v2beta1.Documents.ImportDocuments]. + + Attributes: + warnings (Sequence[google.rpc.status_pb2.Status]): + Includes details about skipped documents or + any other warnings. + """ + + warnings = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + + +class DeleteDocumentRequest(proto.Message): + r"""Request message for + [Documents.DeleteDocument][google.cloud.dialogflow.v2beta1.Documents.DeleteDocument]. + + Attributes: + name (str): + Required. The name of the document to delete. Format: + ``projects//locations//knowledgeBases//documents/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateDocumentRequest(proto.Message): + r"""Request message for + [Documents.UpdateDocument][google.cloud.dialogflow.v2beta1.Documents.UpdateDocument]. + + Attributes: + document (google.cloud.dialogflow_v2beta1.types.Document): + Required. The document to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Not specified means ``update all``. Currently, + only ``display_name`` can be updated, an InvalidArgument + will be returned for attempting to update other fields. + """ + + document = proto.Field( + proto.MESSAGE, + number=1, + message='Document', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class KnowledgeOperationMetadata(proto.Message): + r"""Metadata in google::longrunning::Operation for Knowledge + operations. + + Attributes: + state (google.cloud.dialogflow_v2beta1.types.KnowledgeOperationMetadata.State): + Required. Output only. The current state of + this operation. + knowledge_base (str): + The name of the knowledge base interacted + with during the operation. + """ + class State(proto.Enum): + r"""States of the operation.""" + STATE_UNSPECIFIED = 0 + PENDING = 1 + RUNNING = 2 + DONE = 3 + + state = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + knowledge_base = proto.Field( + proto.STRING, + number=3, + ) + + +class ReloadDocumentRequest(proto.Message): + r"""Request message for + [Documents.ReloadDocument][google.cloud.dialogflow.v2beta1.Documents.ReloadDocument]. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Required. The name of the document to reload. Format: + ``projects//locations//knowledgeBases//documents/`` + gcs_source (google.cloud.dialogflow_v2beta1.types.GcsSource): + The path for a Cloud Storage source file for + reloading document content. If not provided, the + Document's existing source will be reloaded. + + This field is a member of `oneof`_ ``source``. + import_gcs_custom_metadata (bool): + Whether to import custom metadata from Google + Cloud Storage. Only valid when the document + source is Google Cloud Storage URI. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + gcs_source = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message=gcs.GcsSource, + ) + import_gcs_custom_metadata = proto.Field( + proto.BOOL, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/entity_type.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/entity_type.py new file mode 100644 index 000000000..4c0620e7e --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/entity_type.py @@ -0,0 +1,598 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2beta1', + manifest={ + 'EntityType', + 'ListEntityTypesRequest', + 'ListEntityTypesResponse', + 'GetEntityTypeRequest', + 'CreateEntityTypeRequest', + 'UpdateEntityTypeRequest', + 'DeleteEntityTypeRequest', + 'BatchUpdateEntityTypesRequest', + 'BatchUpdateEntityTypesResponse', + 'BatchDeleteEntityTypesRequest', + 'BatchCreateEntitiesRequest', + 'BatchUpdateEntitiesRequest', + 'BatchDeleteEntitiesRequest', + 'EntityTypeBatch', + }, +) + + +class EntityType(proto.Message): + r"""Each intent parameter has a type, called the entity type, which + dictates exactly how data from an end-user expression is extracted. + + Dialogflow provides predefined system entities that can match many + common types of data. For example, there are system entities for + matching dates, times, colors, email addresses, and so on. You can + also create your own custom entities for matching custom data. For + example, you could define a vegetable entity that can match the + types of vegetables available for purchase with a grocery store + agent. + + For more information, see the `Entity + guide `__. + + Attributes: + name (str): + The unique identifier of the entity type. Required for + [EntityTypes.UpdateEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.UpdateEntityType] + and + [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes] + methods. Supported formats: + + - ``projects//agent/entityTypes/`` + - ``projects//locations//agent/entityTypes/`` + display_name (str): + Required. The name of the entity type. + kind (google.cloud.dialogflow_v2beta1.types.EntityType.Kind): + Required. Indicates the kind of entity type. + auto_expansion_mode (google.cloud.dialogflow_v2beta1.types.EntityType.AutoExpansionMode): + Optional. Indicates whether the entity type + can be automatically expanded. + entities (Sequence[google.cloud.dialogflow_v2beta1.types.EntityType.Entity]): + Optional. The collection of entity entries + associated with the entity type. + enable_fuzzy_extraction (bool): + Optional. Enables fuzzy entity extraction + during classification. + """ + class Kind(proto.Enum): + r"""Represents kinds of entities.""" + KIND_UNSPECIFIED = 0 + KIND_MAP = 1 + KIND_LIST = 2 + KIND_REGEXP = 3 + + class AutoExpansionMode(proto.Enum): + r"""Represents different entity type expansion modes. Automated + expansion allows an agent to recognize values that have not been + explicitly listed in the entity (for example, new kinds of + shopping list items). + """ + AUTO_EXPANSION_MODE_UNSPECIFIED = 0 + AUTO_EXPANSION_MODE_DEFAULT = 1 + + class Entity(proto.Message): + r"""An **entity entry** for an associated entity type. + + Attributes: + value (str): + Required. The primary value associated with this entity + entry. For example, if the entity type is *vegetable*, the + value could be *scallions*. + + For ``KIND_MAP`` entity types: + + - A reference value to be used in place of synonyms. + + For ``KIND_LIST`` entity types: + + - A string that can contain references to other entity + types (with or without aliases). + synonyms (Sequence[str]): + Required. A collection of value synonyms. For example, if + the entity type is *vegetable*, and ``value`` is + *scallions*, a synonym could be *green onions*. + + For ``KIND_LIST`` entity types: + + - This collection must contain exactly one synonym equal to + ``value``. + """ + + value = proto.Field( + proto.STRING, + number=1, + ) + synonyms = proto.RepeatedField( + proto.STRING, + number=2, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + kind = proto.Field( + proto.ENUM, + number=3, + enum=Kind, + ) + auto_expansion_mode = proto.Field( + proto.ENUM, + number=4, + enum=AutoExpansionMode, + ) + entities = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=Entity, + ) + enable_fuzzy_extraction = proto.Field( + proto.BOOL, + number=7, + ) + + +class ListEntityTypesRequest(proto.Message): + r"""The request message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.ListEntityTypes]. + + Attributes: + parent (str): + Required. The agent to list all entity types from. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class ListEntityTypesResponse(proto.Message): + r"""The response message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.ListEntityTypes]. + + Attributes: + entity_types (Sequence[google.cloud.dialogflow_v2beta1.types.EntityType]): + The list of agent entity types. There will be a maximum + number of items returned based on the page_size field in the + request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + entity_types = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='EntityType', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetEntityTypeRequest(proto.Message): + r"""The request message for + [EntityTypes.GetEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.GetEntityType]. + + Attributes: + name (str): + Required. The name of the entity type. Supported formats: + + - ``projects//agent/entityTypes/`` + - ``projects//locations//agent/entityTypes/`` + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateEntityTypeRequest(proto.Message): + r"""The request message for + [EntityTypes.CreateEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.CreateEntityType]. + + Attributes: + parent (str): + Required. The agent to create a entity type for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + entity_type (google.cloud.dialogflow_v2beta1.types.EntityType): + Required. The entity type to create. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + entity_type = proto.Field( + proto.MESSAGE, + number=2, + message='EntityType', + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateEntityTypeRequest(proto.Message): + r"""The request message for + [EntityTypes.UpdateEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.UpdateEntityType]. + + Attributes: + entity_type (google.cloud.dialogflow_v2beta1.types.EntityType): + Required. The entity type to update. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which fields + get updated. + """ + + entity_type = proto.Field( + proto.MESSAGE, + number=1, + message='EntityType', + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteEntityTypeRequest(proto.Message): + r"""The request message for + [EntityTypes.DeleteEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.DeleteEntityType]. + + Attributes: + name (str): + Required. The name of the entity type to delete. Supported + formats: + + - ``projects//agent/entityTypes/`` + - ``projects//locations//agent/entityTypes/`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class BatchUpdateEntityTypesRequest(proto.Message): + r"""The request message for + [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The name of the agent to update or create entity + types in. Supported formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + entity_type_batch_uri (str): + The URI to a Google Cloud Storage file + containing entity types to update or create. The + file format can either be a serialized proto (of + EntityBatch type) or a JSON object. Note: The + URI must start with "gs://". + + This field is a member of `oneof`_ ``entity_type_batch``. + entity_type_batch_inline (google.cloud.dialogflow_v2beta1.types.EntityTypeBatch): + The collection of entity types to update or + create. + + This field is a member of `oneof`_ ``entity_type_batch``. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which fields + get updated. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + entity_type_batch_uri = proto.Field( + proto.STRING, + number=2, + oneof='entity_type_batch', + ) + entity_type_batch_inline = proto.Field( + proto.MESSAGE, + number=3, + oneof='entity_type_batch', + message='EntityTypeBatch', + ) + language_code = proto.Field( + proto.STRING, + number=4, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + + +class BatchUpdateEntityTypesResponse(proto.Message): + r"""The response message for + [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes]. + + Attributes: + entity_types (Sequence[google.cloud.dialogflow_v2beta1.types.EntityType]): + The collection of updated or created entity + types. + """ + + entity_types = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='EntityType', + ) + + +class BatchDeleteEntityTypesRequest(proto.Message): + r"""The request message for + [EntityTypes.BatchDeleteEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchDeleteEntityTypes]. + + Attributes: + parent (str): + Required. The name of the agent to delete all entities types + for. Supported formats: + + - ``projects//agent``, + - ``projects//locations//agent``. + entity_type_names (Sequence[str]): + Required. The names entity types to delete. All names must + point to the same agent as ``parent``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + entity_type_names = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class BatchCreateEntitiesRequest(proto.Message): + r"""The request message for + [EntityTypes.BatchCreateEntities][google.cloud.dialogflow.v2beta1.EntityTypes.BatchCreateEntities]. + + Attributes: + parent (str): + Required. The name of the entity type to create entities in. + Supported formats: + + - ``projects//agent/entityTypes/`` + - ``projects//locations//agent/entityTypes/`` + entities (Sequence[google.cloud.dialogflow_v2beta1.types.EntityType.Entity]): + Required. The entities to create. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + entities = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='EntityType.Entity', + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class BatchUpdateEntitiesRequest(proto.Message): + r"""The request message for + [EntityTypes.BatchUpdateEntities][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntities]. + + Attributes: + parent (str): + Required. The name of the entity type to update or create + entities in. Supported formats: + + - ``projects//agent/entityTypes/`` + - ``projects//locations//agent/entityTypes/`` + entities (Sequence[google.cloud.dialogflow_v2beta1.types.EntityType.Entity]): + Required. The entities to update or create. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which fields + get updated. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + entities = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='EntityType.Entity', + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + + +class BatchDeleteEntitiesRequest(proto.Message): + r"""The request message for + [EntityTypes.BatchDeleteEntities][google.cloud.dialogflow.v2beta1.EntityTypes.BatchDeleteEntities]. + + Attributes: + parent (str): + Required. The name of the entity type to delete entries for. + Supported formats: + + - ``projects//agent/entityTypes/`` + - ``projects//locations//agent/entityTypes/`` + entity_values (Sequence[str]): + Required. The reference ``values`` of the entities to + delete. Note that these are not fully-qualified names, i.e. + they don't start with ``projects/``. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + entity_values = proto.RepeatedField( + proto.STRING, + number=2, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class EntityTypeBatch(proto.Message): + r"""This message is a wrapper around a collection of entity + types. + + Attributes: + entity_types (Sequence[google.cloud.dialogflow_v2beta1.types.EntityType]): + A collection of entity types. + """ + + entity_types = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='EntityType', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/environment.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/environment.py new file mode 100644 index 000000000..d47c91972 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/environment.py @@ -0,0 +1,460 @@ +# -*- 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.dialogflow_v2beta1.types import audio_config +from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2beta1', + manifest={ + 'Environment', + 'TextToSpeechSettings', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'GetEnvironmentRequest', + 'CreateEnvironmentRequest', + 'UpdateEnvironmentRequest', + 'DeleteEnvironmentRequest', + 'GetEnvironmentHistoryRequest', + 'EnvironmentHistory', + }, +) + + +class Environment(proto.Message): + r"""You can create multiple versions of your agent and publish them to + separate environments. + + When you edit an agent, you are editing the draft agent. At any + point, you can save the draft agent as an agent version, which is an + immutable snapshot of your agent. + + When you save the draft agent, it is published to the default + environment. When you create agent versions, you can publish them to + custom environments. You can create a variety of custom environments + for: + + - testing + - development + - production + - etc. + + For more information, see the `versions and environments + guide `__. + + Attributes: + name (str): + Output only. The unique identifier of this agent + environment. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + description (str): + Optional. The developer-provided description + for this environment. The maximum length is 500 + characters. If exceeded, the request is + rejected. + agent_version (str): + Optional. The agent version loaded into this environment. + Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + state (google.cloud.dialogflow_v2beta1.types.Environment.State): + Output only. The state of this environment. + This field is read-only, i.e., it cannot be set + by create and update methods. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last update time of this + environment. This field is read-only, i.e., it + cannot be set by create and update methods. + text_to_speech_settings (google.cloud.dialogflow_v2beta1.types.TextToSpeechSettings): + Optional. Text to speech settings for this + environment. + fulfillment (google.cloud.dialogflow_v2beta1.types.Fulfillment): + Optional. The fulfillment settings to use for + this environment. + """ + class State(proto.Enum): + r"""Represents an environment state. When an environment is pointed to a + new agent version, the environment is temporarily set to the + ``LOADING`` state. During that time, the environment keeps on + serving the previous version of the agent. After the new agent + version is done loading, the environment is set back to the + ``RUNNING`` state. + """ + STATE_UNSPECIFIED = 0 + STOPPED = 1 + LOADING = 2 + RUNNING = 3 + + name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + agent_version = proto.Field( + proto.STRING, + number=3, + ) + state = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + update_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + text_to_speech_settings = proto.Field( + proto.MESSAGE, + number=7, + message='TextToSpeechSettings', + ) + fulfillment = proto.Field( + proto.MESSAGE, + number=8, + message=gcd_fulfillment.Fulfillment, + ) + + +class TextToSpeechSettings(proto.Message): + r"""Instructs the speech synthesizer on how to generate the + output audio content. + + Attributes: + enable_text_to_speech (bool): + Optional. Indicates whether text to speech is + enabled. Even when this field is false, other + settings in this proto are still retained. + output_audio_encoding (google.cloud.dialogflow_v2beta1.types.OutputAudioEncoding): + Required. Audio encoding of the synthesized + audio content. + sample_rate_hertz (int): + Optional. The synthesis sample rate (in + hertz) for this audio. If not provided, then the + synthesizer will use the default sample rate + based on the audio encoding. If this is + different from the voice's natural sample rate, + then the synthesizer will honor this request by + converting to the desired sample rate (which + might result in worse audio quality). + synthesize_speech_configs (Sequence[google.cloud.dialogflow_v2beta1.types.TextToSpeechSettings.SynthesizeSpeechConfigsEntry]): + Optional. Configuration of how speech should + be synthesized, mapping from language + (https://cloud.google.com/dialogflow/docs/reference/language) + to SynthesizeSpeechConfig. + """ + + enable_text_to_speech = proto.Field( + proto.BOOL, + number=1, + ) + output_audio_encoding = proto.Field( + proto.ENUM, + number=2, + enum=audio_config.OutputAudioEncoding, + ) + sample_rate_hertz = proto.Field( + proto.INT32, + number=3, + ) + synthesize_speech_configs = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message=audio_config.SynthesizeSpeechConfig, + ) + + +class ListEnvironmentsRequest(proto.Message): + r"""The request message for + [Environments.ListEnvironments][google.cloud.dialogflow.v2beta1.Environments.ListEnvironments]. + + Attributes: + parent (str): + Required. The agent to list all environments from. Format: + + - ``projects//agent`` + - ``projects//locations//agent`` + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListEnvironmentsResponse(proto.Message): + r"""The response message for + [Environments.ListEnvironments][google.cloud.dialogflow.v2beta1.Environments.ListEnvironments]. + + Attributes: + environments (Sequence[google.cloud.dialogflow_v2beta1.types.Environment]): + The list of agent environments. There will be a maximum + number of items returned based on the page_size field in the + request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + environments = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Environment', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.v2beta1.Environments.GetEnvironment]. + + Attributes: + name (str): + Required. The name of the environment. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.v2beta1.Environments.CreateEnvironment]. + + Attributes: + parent (str): + Required. The agent to create an environment for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + environment (google.cloud.dialogflow_v2beta1.types.Environment): + Required. The environment to create. + environment_id (str): + Required. The unique id of the new + environment. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + environment = proto.Field( + proto.MESSAGE, + number=2, + message='Environment', + ) + environment_id = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.v2beta1.Environments.UpdateEnvironment]. + + Attributes: + environment (google.cloud.dialogflow_v2beta1.types.Environment): + Required. The environment to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. + allow_load_to_draft_and_discard_changes (bool): + Optional. This field is used to prevent accidental overwrite + of the draft environment, which is an operation that cannot + be undone. To confirm that the caller desires this + overwrite, this field must be explicitly set to true when + updating the draft environment (environment ID = ``-``). + """ + + environment = proto.Field( + proto.MESSAGE, + number=1, + message='Environment', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_load_to_draft_and_discard_changes = proto.Field( + proto.BOOL, + number=3, + ) + + +class DeleteEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.v2beta1.Environments.DeleteEnvironment]. + + Attributes: + name (str): + Required. The name of the environment to delete. / Format: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetEnvironmentHistoryRequest(proto.Message): + r"""The request message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. + + Attributes: + parent (str): + Required. The name of the environment to retrieve history + for. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class EnvironmentHistory(proto.Message): + r"""The response message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. + + Attributes: + parent (str): + Output only. The name of the environment this history is + for. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + entries (Sequence[google.cloud.dialogflow_v2beta1.types.EnvironmentHistory.Entry]): + Output only. The list of agent environments. There will be a + maximum number of items returned based on the page_size + field in the request. + next_page_token (str): + Output only. Token to retrieve the next page + of results, or empty if there are no more + results in the list. + """ + + class Entry(proto.Message): + r"""Represents an environment history entry. + + Attributes: + agent_version (str): + The agent version loaded into this + environment history entry. + description (str): + The developer-provided description for this + environment history entry. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The creation time of this environment history + entry. + """ + + agent_version = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + create_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + @property + def raw_page(self): + return self + + parent = proto.Field( + proto.STRING, + number=1, + ) + entries = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Entry, + ) + next_page_token = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/fulfillment.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/fulfillment.py new file mode 100644 index 000000000..7c9be6c72 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/fulfillment.py @@ -0,0 +1,207 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2beta1', + manifest={ + 'Fulfillment', + 'GetFulfillmentRequest', + 'UpdateFulfillmentRequest', + }, +) + + +class Fulfillment(proto.Message): + r"""By default, your agent responds to a matched intent with a static + response. As an alternative, you can provide a more dynamic response + by using fulfillment. When you enable fulfillment for an intent, + Dialogflow responds to that intent by calling a service that you + define. For example, if an end-user wants to schedule a haircut on + Friday, your service can check your database and respond to the + end-user with availability information for Friday. + + For more information, see the `fulfillment + guide `__. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Required. The unique identifier of the fulfillment. + Supported formats: + + - ``projects//agent/fulfillment`` + - ``projects//locations//agent/fulfillment`` + + This field is not used for Fulfillment in an Environment. + display_name (str): + The human-readable name of the fulfillment, + unique within the agent. + This field is not used for Fulfillment in an + Environment. + generic_web_service (google.cloud.dialogflow_v2beta1.types.Fulfillment.GenericWebService): + Configuration for a generic web service. + + This field is a member of `oneof`_ ``fulfillment``. + enabled (bool): + Whether fulfillment is enabled. + features (Sequence[google.cloud.dialogflow_v2beta1.types.Fulfillment.Feature]): + The field defines whether the fulfillment is + enabled for certain features. + """ + + class GenericWebService(proto.Message): + r"""Represents configuration for a generic web service. + Dialogflow supports two mechanisms for authentications: - Basic + authentication with username and password. + - Authentication with additional authentication headers. More + information could be found at: + https://cloud.google.com/dialogflow/docs/fulfillment-configure. + + Attributes: + uri (str): + Required. The fulfillment URI for receiving + POST requests. It must use https protocol. + username (str): + The user name for HTTP Basic authentication. + password (str): + The password for HTTP Basic authentication. + request_headers (Sequence[google.cloud.dialogflow_v2beta1.types.Fulfillment.GenericWebService.RequestHeadersEntry]): + The HTTP request headers to send together + with fulfillment requests. + is_cloud_function (bool): + Optional. Indicates if generic web service is created + through Cloud Functions integration. Defaults to false. + + is_cloud_function is deprecated. Cloud functions can be + configured by its uri as a regular web service now. + """ + + uri = proto.Field( + proto.STRING, + number=1, + ) + username = proto.Field( + proto.STRING, + number=2, + ) + password = proto.Field( + proto.STRING, + number=3, + ) + request_headers = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + is_cloud_function = proto.Field( + proto.BOOL, + number=5, + ) + + class Feature(proto.Message): + r"""Whether fulfillment is enabled for the specific feature. + + Attributes: + type_ (google.cloud.dialogflow_v2beta1.types.Fulfillment.Feature.Type): + The type of the feature that enabled for + fulfillment. + """ + class Type(proto.Enum): + r"""The type of the feature.""" + TYPE_UNSPECIFIED = 0 + SMALLTALK = 1 + + type_ = proto.Field( + proto.ENUM, + number=1, + enum='Fulfillment.Feature.Type', + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + generic_web_service = proto.Field( + proto.MESSAGE, + number=3, + oneof='fulfillment', + message=GenericWebService, + ) + enabled = proto.Field( + proto.BOOL, + number=4, + ) + features = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=Feature, + ) + + +class GetFulfillmentRequest(proto.Message): + r"""The request message for + [Fulfillments.GetFulfillment][google.cloud.dialogflow.v2beta1.Fulfillments.GetFulfillment]. + + Attributes: + name (str): + Required. The name of the fulfillment. Supported formats: + + - ``projects//agent/fulfillment`` + - ``projects//locations//agent/fulfillment`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateFulfillmentRequest(proto.Message): + r"""The request message for + [Fulfillments.UpdateFulfillment][google.cloud.dialogflow.v2beta1.Fulfillments.UpdateFulfillment]. + + Attributes: + fulfillment (google.cloud.dialogflow_v2beta1.types.Fulfillment): + Required. The fulfillment to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. If the mask is not present, all + fields will be updated. + """ + + fulfillment = proto.Field( + proto.MESSAGE, + number=1, + message='Fulfillment', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/gcs.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/gcs.py new file mode 100644 index 000000000..8256ee2c4 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/gcs.py @@ -0,0 +1,64 @@ +# -*- 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.dialogflow.v2beta1', + manifest={ + 'GcsSources', + 'GcsSource', + }, +) + + +class GcsSources(proto.Message): + r"""Google Cloud Storage locations for the inputs. + + Attributes: + uris (Sequence[str]): + Required. Google Cloud Storage URIs for the + inputs. A URI is of the form: + gs://bucket/object-prefix-or-name + Whether a prefix or name is used depends on the + use case. + """ + + uris = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class GcsSource(proto.Message): + r"""Google Cloud Storage location for single input. + + Attributes: + uri (str): + Required. The Google Cloud Storage URIs for + the inputs. A URI is of the form: + gs://bucket/object-prefix-or-name + Whether a prefix or name is used depends on the + use case. + """ + + uri = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/human_agent_assistant_event.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/human_agent_assistant_event.py new file mode 100644 index 000000000..0473ecffe --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/human_agent_assistant_event.py @@ -0,0 +1,69 @@ +# -*- 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.dialogflow_v2beta1.types import participant as gcd_participant + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2beta1', + manifest={ + 'HumanAgentAssistantEvent', + }, +) + + +class HumanAgentAssistantEvent(proto.Message): + r"""Output only. Represents a notification sent to Pub/Sub + subscribers for agent assistant events in a specific + conversation. + + Attributes: + conversation (str): + The conversation this notification refers to. Format: + ``projects//conversations/``. + participant (str): + The participant that the suggestion is compiled for. And + This field is used to call + [Participants.ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions] + API. Format: + ``projects//conversations//participants/``. + It will not be set in legacy workflow. + [HumanAgentAssistantConfig.name][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.name] + for more information. + suggestion_results (Sequence[google.cloud.dialogflow_v2beta1.types.SuggestionResult]): + The suggestion results payload that this notification refers + to. It will only be set when + [HumanAgentAssistantConfig.SuggestionConfig.group_suggestion_responses][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.SuggestionConfig.group_suggestion_responses] + sets to true. + """ + + conversation = proto.Field( + proto.STRING, + number=1, + ) + participant = proto.Field( + proto.STRING, + number=3, + ) + suggestion_results = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=gcd_participant.SuggestionResult, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/intent.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/intent.py new file mode 100644 index 000000000..e11a8666e --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/intent.py @@ -0,0 +1,2267 @@ +# -*- 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.dialogflow_v2beta1.types import context +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2beta1', + manifest={ + 'IntentView', + 'Intent', + 'ListIntentsRequest', + 'ListIntentsResponse', + 'GetIntentRequest', + 'CreateIntentRequest', + 'UpdateIntentRequest', + 'DeleteIntentRequest', + 'BatchUpdateIntentsRequest', + 'BatchUpdateIntentsResponse', + 'BatchDeleteIntentsRequest', + 'IntentBatch', + }, +) + + +class IntentView(proto.Enum): + r"""Represents the options for views of an intent. + An intent can be a sizable object. Therefore, we provide a + resource view that does not return training phrases in the + response by default. + """ + INTENT_VIEW_UNSPECIFIED = 0 + INTENT_VIEW_FULL = 1 + + +class Intent(proto.Message): + r"""An intent categorizes an end-user's intention for one conversation + turn. For each agent, you define many intents, where your combined + intents can handle a complete conversation. When an end-user writes + or says something, referred to as an end-user expression or end-user + input, Dialogflow matches the end-user input to the best intent in + your agent. Matching an intent is also known as intent + classification. + + For more information, see the `intent + guide `__. + + Attributes: + name (str): + Optional. The unique identifier of this intent. Required for + [Intents.UpdateIntent][google.cloud.dialogflow.v2beta1.Intents.UpdateIntent] + and + [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2beta1.Intents.BatchUpdateIntents] + methods. Supported formats: + + - ``projects//agent/intents/`` + - ``projects//locations//agent/intents/`` + display_name (str): + Required. The name of this intent. + webhook_state (google.cloud.dialogflow_v2beta1.types.Intent.WebhookState): + Optional. Indicates whether webhooks are + enabled for the intent. + priority (int): + Optional. The priority of this intent. Higher numbers + represent higher priorities. + + - If the supplied value is unspecified or 0, the service + translates the value to 500,000, which corresponds to the + ``Normal`` priority in the console. + - If the supplied value is negative, the intent is ignored + in runtime detect intent requests. + is_fallback (bool): + Optional. Indicates whether this is a + fallback intent. + ml_enabled (bool): + Optional. Indicates whether Machine Learning is enabled for + the intent. Note: If ``ml_enabled`` setting is set to false, + then this intent is not taken into account during inference + in ``ML ONLY`` match mode. Also, auto-markup in the UI is + turned off. DEPRECATED! Please use ``ml_disabled`` field + instead. NOTE: If both ``ml_enabled`` and ``ml_disabled`` + are either not set or false, then the default value is + determined as follows: + + - Before April 15th, 2018 the default is: ml_enabled = + false / ml_disabled = true. + - After April 15th, 2018 the default is: ml_enabled = true + / ml_disabled = false. + ml_disabled (bool): + Optional. Indicates whether Machine Learning is disabled for + the intent. Note: If ``ml_disabled`` setting is set to true, + then this intent is not taken into account during inference + in ``ML ONLY`` match mode. Also, auto-markup in the UI is + turned off. + live_agent_handoff (bool): + Optional. Indicates that a live agent should be brought in + to handle the interaction with the user. In most cases, when + you set this flag to true, you would also want to set + end_interaction to true as well. Default is false. + end_interaction (bool): + Optional. Indicates that this intent ends an + interaction. Some integrations (e.g., Actions on + Google or Dialogflow phone gateway) use this + information to close interaction with an end + user. Default is false. + input_context_names (Sequence[str]): + Optional. The list of context names required for this intent + to be triggered. Formats: + + - ``projects//agent/sessions/-/contexts/`` + - ``projects//locations//agent/sessions/-/contexts/`` + events (Sequence[str]): + Optional. The collection of event names that + trigger the intent. If the collection of input + contexts is not empty, all of the contexts must + be present in the active user session for an + event to trigger this intent. Event names are + limited to 150 characters. + training_phrases (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.TrainingPhrase]): + Optional. The collection of examples that the + agent is trained on. + action (str): + Optional. The name of the action associated + with the intent. Note: The action name must not + contain whitespaces. + output_contexts (Sequence[google.cloud.dialogflow_v2beta1.types.Context]): + Optional. The collection of contexts that are activated when + the intent is matched. Context messages in this collection + should not set the parameters field. Setting the + ``lifespan_count`` to 0 will reset the context when the + intent is matched. Format: + ``projects//agent/sessions/-/contexts/``. + reset_contexts (bool): + Optional. Indicates whether to delete all + contexts in the current session when this intent + is matched. + parameters (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Parameter]): + Optional. The collection of parameters + associated with the intent. + messages (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message]): + Optional. The collection of rich messages corresponding to + the ``Response`` field in the Dialogflow console. + default_response_platforms (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.Platform]): + Optional. The list of platforms for which the first + responses will be copied from the messages in + PLATFORM_UNSPECIFIED (i.e. default platform). + root_followup_intent_name (str): + Output only. The unique identifier of the root intent in the + chain of followup intents. It identifies the correct + followup intents chain for this intent. + + Format: ``projects//agent/intents/``. + parent_followup_intent_name (str): + Optional. The unique identifier of the parent intent in the + chain of followup intents. You can set this field when + creating an intent, for example with + [CreateIntent][google.cloud.dialogflow.v2beta1.Intents.CreateIntent] + or + [BatchUpdateIntents][google.cloud.dialogflow.v2beta1.Intents.BatchUpdateIntents], + in order to make this intent a followup intent. + + It identifies the parent followup intent. Format: + ``projects//agent/intents/``. + followup_intent_info (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.FollowupIntentInfo]): + Output only. Information about all followup + intents that have this intent as a direct or + indirect parent. We populate this field only in + the output. + """ + class WebhookState(proto.Enum): + r"""Represents the different states that webhooks can be in.""" + WEBHOOK_STATE_UNSPECIFIED = 0 + WEBHOOK_STATE_ENABLED = 1 + WEBHOOK_STATE_ENABLED_FOR_SLOT_FILLING = 2 + + class TrainingPhrase(proto.Message): + r"""Represents an example that the agent is trained on. + + Attributes: + name (str): + Output only. The unique identifier of this + training phrase. + type_ (google.cloud.dialogflow_v2beta1.types.Intent.TrainingPhrase.Type): + Required. The type of the training phrase. + parts (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.TrainingPhrase.Part]): + Required. The ordered list of training phrase parts. The + parts are concatenated in order to form the training phrase. + + Note: The API does not automatically annotate training + phrases like the Dialogflow Console does. + + Note: Do not forget to include whitespace at part + boundaries, so the training phrase is well formatted when + the parts are concatenated. + + If the training phrase does not need to be annotated with + parameters, you just need a single part with only the + [Part.text][google.cloud.dialogflow.v2beta1.Intent.TrainingPhrase.Part.text] + field set. + + If you want to annotate the training phrase, you must create + multiple parts, where the fields of each part are populated + in one of two ways: + + - ``Part.text`` is set to a part of the phrase that has no + parameters. + - ``Part.text`` is set to a part of the phrase that you + want to annotate, and the ``entity_type``, ``alias``, and + ``user_defined`` fields are all set. + times_added_count (int): + Optional. Indicates how many times this + example was added to the intent. Each time a + developer adds an existing sample by editing an + intent or training, this counter is increased. + """ + class Type(proto.Enum): + r"""Represents different types of training phrases.""" + TYPE_UNSPECIFIED = 0 + EXAMPLE = 1 + TEMPLATE = 2 + + class Part(proto.Message): + r"""Represents a part of a training phrase. + + Attributes: + text (str): + Required. The text for this part. + entity_type (str): + Optional. The entity type name prefixed with ``@``. This + field is required for annotated parts of the training + phrase. + alias (str): + Optional. The parameter name for the value + extracted from the annotated part of the + example. This field is required for annotated + parts of the training phrase. + user_defined (bool): + Optional. Indicates whether the text was + manually annotated. This field is set to true + when the Dialogflow Console is used to manually + annotate the part. When creating an annotated + part with the API, you must set this to true. + """ + + text = proto.Field( + proto.STRING, + number=1, + ) + entity_type = proto.Field( + proto.STRING, + number=2, + ) + alias = proto.Field( + proto.STRING, + number=3, + ) + user_defined = proto.Field( + proto.BOOL, + number=4, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.ENUM, + number=2, + enum='Intent.TrainingPhrase.Type', + ) + parts = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Intent.TrainingPhrase.Part', + ) + times_added_count = proto.Field( + proto.INT32, + number=4, + ) + + class Parameter(proto.Message): + r"""Represents intent parameters. + + Attributes: + name (str): + The unique identifier of this parameter. + display_name (str): + Required. The name of the parameter. + value (str): + Optional. The definition of the parameter value. It can be: + + - a constant string, + - a parameter value defined as ``$parameter_name``, + - an original parameter value defined as + ``$parameter_name.original``, + - a parameter value from some context defined as + ``#context_name.parameter_name``. + default_value (str): + Optional. The default value to use when the ``value`` yields + an empty result. Default values can be extracted from + contexts by using the following syntax: + ``#context_name.parameter_name``. + entity_type_display_name (str): + Optional. The name of the entity type, prefixed with ``@``, + that describes values of the parameter. If the parameter is + required, this must be provided. + mandatory (bool): + Optional. Indicates whether the parameter is + required. That is, whether the intent cannot be + completed without collecting the parameter + value. + prompts (Sequence[str]): + Optional. The collection of prompts that the + agent can present to the user in order to + collect a value for the parameter. + is_list (bool): + Optional. Indicates whether the parameter + represents a list of values. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + value = proto.Field( + proto.STRING, + number=3, + ) + default_value = proto.Field( + proto.STRING, + number=4, + ) + entity_type_display_name = proto.Field( + proto.STRING, + number=5, + ) + mandatory = proto.Field( + proto.BOOL, + number=6, + ) + prompts = proto.RepeatedField( + proto.STRING, + number=7, + ) + is_list = proto.Field( + proto.BOOL, + number=8, + ) + + class Message(proto.Message): + r"""Corresponds to the ``Response`` field in the Dialogflow console. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + text (google.cloud.dialogflow_v2beta1.types.Intent.Message.Text): + Returns a text response. + + This field is a member of `oneof`_ ``message``. + image (google.cloud.dialogflow_v2beta1.types.Intent.Message.Image): + Displays an image. + + This field is a member of `oneof`_ ``message``. + quick_replies (google.cloud.dialogflow_v2beta1.types.Intent.Message.QuickReplies): + Displays quick replies. + + This field is a member of `oneof`_ ``message``. + card (google.cloud.dialogflow_v2beta1.types.Intent.Message.Card): + Displays a card. + + This field is a member of `oneof`_ ``message``. + payload (google.protobuf.struct_pb2.Struct): + A custom platform-specific response. + + This field is a member of `oneof`_ ``message``. + simple_responses (google.cloud.dialogflow_v2beta1.types.Intent.Message.SimpleResponses): + Returns a voice or text-only response for + Actions on Google. + + This field is a member of `oneof`_ ``message``. + basic_card (google.cloud.dialogflow_v2beta1.types.Intent.Message.BasicCard): + Displays a basic card for Actions on Google. + + This field is a member of `oneof`_ ``message``. + suggestions (google.cloud.dialogflow_v2beta1.types.Intent.Message.Suggestions): + Displays suggestion chips for Actions on + Google. + + This field is a member of `oneof`_ ``message``. + link_out_suggestion (google.cloud.dialogflow_v2beta1.types.Intent.Message.LinkOutSuggestion): + Displays a link out suggestion chip for + Actions on Google. + + This field is a member of `oneof`_ ``message``. + list_select (google.cloud.dialogflow_v2beta1.types.Intent.Message.ListSelect): + Displays a list card for Actions on Google. + + This field is a member of `oneof`_ ``message``. + carousel_select (google.cloud.dialogflow_v2beta1.types.Intent.Message.CarouselSelect): + Displays a carousel card for Actions on + Google. + + This field is a member of `oneof`_ ``message``. + telephony_play_audio (google.cloud.dialogflow_v2beta1.types.Intent.Message.TelephonyPlayAudio): + Plays audio from a file in Telephony Gateway. + + This field is a member of `oneof`_ ``message``. + telephony_synthesize_speech (google.cloud.dialogflow_v2beta1.types.Intent.Message.TelephonySynthesizeSpeech): + Synthesizes speech in Telephony Gateway. + + This field is a member of `oneof`_ ``message``. + telephony_transfer_call (google.cloud.dialogflow_v2beta1.types.Intent.Message.TelephonyTransferCall): + Transfers the call in Telephony Gateway. + + This field is a member of `oneof`_ ``message``. + rbm_text (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmText): + Rich Business Messaging (RBM) text response. + RBM allows businesses to send enriched and + branded versions of SMS. See + https://jibe.google.com/business-messaging. + + This field is a member of `oneof`_ ``message``. + rbm_standalone_rich_card (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmStandaloneCard): + Standalone Rich Business Messaging (RBM) rich + card response. + + This field is a member of `oneof`_ ``message``. + rbm_carousel_rich_card (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmCarouselCard): + Rich Business Messaging (RBM) carousel rich + card response. + + This field is a member of `oneof`_ ``message``. + browse_carousel_card (google.cloud.dialogflow_v2beta1.types.Intent.Message.BrowseCarouselCard): + Browse carousel card for Actions on Google. + + This field is a member of `oneof`_ ``message``. + table_card (google.cloud.dialogflow_v2beta1.types.Intent.Message.TableCard): + Table card for Actions on Google. + + This field is a member of `oneof`_ ``message``. + media_content (google.cloud.dialogflow_v2beta1.types.Intent.Message.MediaContent): + The media content card for Actions on Google. + + This field is a member of `oneof`_ ``message``. + platform (google.cloud.dialogflow_v2beta1.types.Intent.Message.Platform): + Optional. The platform that this message is + intended for. + """ + class Platform(proto.Enum): + r"""Represents different platforms that a rich message can be + intended for. + """ + PLATFORM_UNSPECIFIED = 0 + FACEBOOK = 1 + SLACK = 2 + TELEGRAM = 3 + KIK = 4 + SKYPE = 5 + LINE = 6 + VIBER = 7 + ACTIONS_ON_GOOGLE = 8 + TELEPHONY = 10 + GOOGLE_HANGOUTS = 11 + + class Text(proto.Message): + r"""The text response message. + + Attributes: + text (Sequence[str]): + Optional. The collection of the agent's + responses. + """ + + text = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class Image(proto.Message): + r"""The image response message. + + Attributes: + image_uri (str): + Optional. The public URI to an image file. + accessibility_text (str): + A text description of the image to be used for + accessibility, e.g., screen readers. Required if image_uri + is set for CarouselSelect. + """ + + image_uri = proto.Field( + proto.STRING, + number=1, + ) + accessibility_text = proto.Field( + proto.STRING, + number=2, + ) + + class QuickReplies(proto.Message): + r"""The quick replies response message. + + Attributes: + title (str): + Optional. The title of the collection of + quick replies. + quick_replies (Sequence[str]): + Optional. The collection of quick replies. + """ + + title = proto.Field( + proto.STRING, + number=1, + ) + quick_replies = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class Card(proto.Message): + r"""The card response message. + + Attributes: + title (str): + Optional. The title of the card. + subtitle (str): + Optional. The subtitle of the card. + image_uri (str): + Optional. The public URI to an image file for + the card. + buttons (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.Card.Button]): + Optional. The collection of card buttons. + """ + + class Button(proto.Message): + r"""Optional. Contains information about a button. + + Attributes: + text (str): + Optional. The text to show on the button. + postback (str): + Optional. The text to send back to the + Dialogflow API or a URI to open. + """ + + text = proto.Field( + proto.STRING, + number=1, + ) + postback = proto.Field( + proto.STRING, + number=2, + ) + + title = proto.Field( + proto.STRING, + number=1, + ) + subtitle = proto.Field( + proto.STRING, + number=2, + ) + image_uri = proto.Field( + proto.STRING, + number=3, + ) + buttons = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Intent.Message.Card.Button', + ) + + class SimpleResponse(proto.Message): + r"""The simple response message containing speech or text. + + Attributes: + text_to_speech (str): + One of text_to_speech or ssml must be provided. The plain + text of the speech output. Mutually exclusive with ssml. + ssml (str): + One of text_to_speech or ssml must be provided. Structured + spoken response to the user in the SSML format. Mutually + exclusive with text_to_speech. + display_text (str): + Optional. The text to display. + """ + + text_to_speech = proto.Field( + proto.STRING, + number=1, + ) + ssml = proto.Field( + proto.STRING, + number=2, + ) + display_text = proto.Field( + proto.STRING, + number=3, + ) + + class SimpleResponses(proto.Message): + r"""The collection of simple response candidates. This message in + ``QueryResult.fulfillment_messages`` and + ``WebhookResponse.fulfillment_messages`` should contain only one + ``SimpleResponse``. + + Attributes: + simple_responses (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.SimpleResponse]): + Required. The list of simple responses. + """ + + simple_responses = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Intent.Message.SimpleResponse', + ) + + class BasicCard(proto.Message): + r"""The basic card message. Useful for displaying information. + + Attributes: + title (str): + Optional. The title of the card. + subtitle (str): + Optional. The subtitle of the card. + formatted_text (str): + Required, unless image is present. The body + text of the card. + image (google.cloud.dialogflow_v2beta1.types.Intent.Message.Image): + Optional. The image for the card. + buttons (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.BasicCard.Button]): + Optional. The collection of card buttons. + """ + + class Button(proto.Message): + r"""The button object that appears at the bottom of a card. + + Attributes: + title (str): + Required. The title of the button. + open_uri_action (google.cloud.dialogflow_v2beta1.types.Intent.Message.BasicCard.Button.OpenUriAction): + Required. Action to take when a user taps on + the button. + """ + + class OpenUriAction(proto.Message): + r"""Opens the given URI. + + Attributes: + uri (str): + Required. The HTTP or HTTPS scheme URI. + """ + + uri = proto.Field( + proto.STRING, + number=1, + ) + + title = proto.Field( + proto.STRING, + number=1, + ) + open_uri_action = proto.Field( + proto.MESSAGE, + number=2, + message='Intent.Message.BasicCard.Button.OpenUriAction', + ) + + title = proto.Field( + proto.STRING, + number=1, + ) + subtitle = proto.Field( + proto.STRING, + number=2, + ) + formatted_text = proto.Field( + proto.STRING, + number=3, + ) + image = proto.Field( + proto.MESSAGE, + number=4, + message='Intent.Message.Image', + ) + buttons = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='Intent.Message.BasicCard.Button', + ) + + class Suggestion(proto.Message): + r"""The suggestion chip message that the user can tap to quickly + post a reply to the conversation. + + Attributes: + title (str): + Required. The text shown the in the + suggestion chip. + """ + + title = proto.Field( + proto.STRING, + number=1, + ) + + class Suggestions(proto.Message): + r"""The collection of suggestions. + + Attributes: + suggestions (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.Suggestion]): + Required. The list of suggested replies. + """ + + suggestions = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Intent.Message.Suggestion', + ) + + class LinkOutSuggestion(proto.Message): + r"""The suggestion chip message that allows the user to jump out + to the app or website associated with this agent. + + Attributes: + destination_name (str): + Required. The name of the app or site this + chip is linking to. + uri (str): + Required. The URI of the app or site to open + when the user taps the suggestion chip. + """ + + destination_name = proto.Field( + proto.STRING, + number=1, + ) + uri = proto.Field( + proto.STRING, + number=2, + ) + + class ListSelect(proto.Message): + r"""The card for presenting a list of options to select from. + + Attributes: + title (str): + Optional. The overall title of the list. + items (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.ListSelect.Item]): + Required. List items. + subtitle (str): + Optional. Subtitle of the list. + """ + + class Item(proto.Message): + r"""An item in the list. + + Attributes: + info (google.cloud.dialogflow_v2beta1.types.Intent.Message.SelectItemInfo): + Required. Additional information about this + option. + title (str): + Required. The title of the list item. + description (str): + Optional. The main text describing the item. + image (google.cloud.dialogflow_v2beta1.types.Intent.Message.Image): + Optional. The image to display. + """ + + info = proto.Field( + proto.MESSAGE, + number=1, + message='Intent.Message.SelectItemInfo', + ) + title = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + image = proto.Field( + proto.MESSAGE, + number=4, + message='Intent.Message.Image', + ) + + title = proto.Field( + proto.STRING, + number=1, + ) + items = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Intent.Message.ListSelect.Item', + ) + subtitle = proto.Field( + proto.STRING, + number=3, + ) + + class CarouselSelect(proto.Message): + r"""The card for presenting a carousel of options to select from. + + Attributes: + items (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.CarouselSelect.Item]): + Required. Carousel items. + """ + + class Item(proto.Message): + r"""An item in the carousel. + + Attributes: + info (google.cloud.dialogflow_v2beta1.types.Intent.Message.SelectItemInfo): + Required. Additional info about the option + item. + title (str): + Required. Title of the carousel item. + description (str): + Optional. The body text of the card. + image (google.cloud.dialogflow_v2beta1.types.Intent.Message.Image): + Optional. The image to display. + """ + + info = proto.Field( + proto.MESSAGE, + number=1, + message='Intent.Message.SelectItemInfo', + ) + title = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + image = proto.Field( + proto.MESSAGE, + number=4, + message='Intent.Message.Image', + ) + + items = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Intent.Message.CarouselSelect.Item', + ) + + class SelectItemInfo(proto.Message): + r"""Additional info about the select item for when it is + triggered in a dialog. + + Attributes: + key (str): + Required. A unique key that will be sent back + to the agent if this response is given. + synonyms (Sequence[str]): + Optional. A list of synonyms that can also be + used to trigger this item in dialog. + """ + + key = proto.Field( + proto.STRING, + number=1, + ) + synonyms = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class TelephonyPlayAudio(proto.Message): + r"""Plays audio from a file in Telephony Gateway. + + Attributes: + audio_uri (str): + Required. URI to a Google Cloud Storage object containing + the audio to play, e.g., "gs://bucket/object". The object + must contain a single channel (mono) of linear PCM audio (2 + bytes / sample) at 8kHz. + + This object must be readable by the + ``service-@gcp-sa-dialogflow.iam.gserviceaccount.com`` + service account where is the number of the Telephony Gateway + project (usually the same as the Dialogflow agent project). + If the Google Cloud Storage bucket is in the Telephony + Gateway project, this permission is added by default when + enabling the Dialogflow V2 API. + + For audio from other sources, consider using the + ``TelephonySynthesizeSpeech`` message with SSML. + """ + + audio_uri = proto.Field( + proto.STRING, + number=1, + ) + + class TelephonySynthesizeSpeech(proto.Message): + r"""Synthesizes speech and plays back the synthesized audio to the + caller in Telephony Gateway. + + Telephony Gateway takes the synthesizer settings from + ``DetectIntentResponse.output_audio_config`` which can either be set + at request-level or can come from the agent-level synthesizer + config. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + text (str): + The raw text to be synthesized. + + This field is a member of `oneof`_ ``source``. + ssml (str): + The SSML to be synthesized. For more information, see + `SSML `__. + + This field is a member of `oneof`_ ``source``. + """ + + text = proto.Field( + proto.STRING, + number=1, + oneof='source', + ) + ssml = proto.Field( + proto.STRING, + number=2, + oneof='source', + ) + + class TelephonyTransferCall(proto.Message): + r"""Transfers the call in Telephony Gateway. + + Attributes: + phone_number (str): + Required. The phone number to transfer the call to in `E.164 + format `__. + + We currently only allow transferring to US numbers + (+1xxxyyyzzzz). + """ + + phone_number = proto.Field( + proto.STRING, + number=1, + ) + + class RbmText(proto.Message): + r"""Rich Business Messaging (RBM) text response with suggestions. + + Attributes: + text (str): + Required. Text sent and displayed to the + user. + rbm_suggestion (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmSuggestion]): + Optional. One or more suggestions to show to + the user. + """ + + text = proto.Field( + proto.STRING, + number=1, + ) + rbm_suggestion = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Intent.Message.RbmSuggestion', + ) + + class RbmCarouselCard(proto.Message): + r"""Carousel Rich Business Messaging (RBM) rich card. + + Rich cards allow you to respond to users with more vivid content, + e.g. with media and suggestions. + + If you want to show a single card with more control over the layout, + please use + [RbmStandaloneCard][google.cloud.dialogflow.v2beta1.Intent.Message.RbmStandaloneCard] + instead. + + Attributes: + card_width (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmCarouselCard.CardWidth): + Required. The width of the cards in the + carousel. + card_contents (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmCardContent]): + Required. The cards in the carousel. A + carousel must have at least 2 cards and at most + 10. + """ + class CardWidth(proto.Enum): + r"""The width of the cards in the carousel.""" + CARD_WIDTH_UNSPECIFIED = 0 + SMALL = 1 + MEDIUM = 2 + + card_width = proto.Field( + proto.ENUM, + number=1, + enum='Intent.Message.RbmCarouselCard.CardWidth', + ) + card_contents = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Intent.Message.RbmCardContent', + ) + + class RbmStandaloneCard(proto.Message): + r"""Standalone Rich Business Messaging (RBM) rich card. + + Rich cards allow you to respond to users with more vivid content, + e.g. with media and suggestions. + + You can group multiple rich cards into one using + [RbmCarouselCard][google.cloud.dialogflow.v2beta1.Intent.Message.RbmCarouselCard] + but carousel cards will give you less control over the card layout. + + Attributes: + card_orientation (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmStandaloneCard.CardOrientation): + Required. Orientation of the card. + thumbnail_image_alignment (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmStandaloneCard.ThumbnailImageAlignment): + Required if orientation is horizontal. + Image preview alignment for standalone cards + with horizontal layout. + card_content (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmCardContent): + Required. Card content. + """ + class CardOrientation(proto.Enum): + r"""Orientation of the card.""" + CARD_ORIENTATION_UNSPECIFIED = 0 + HORIZONTAL = 1 + VERTICAL = 2 + + class ThumbnailImageAlignment(proto.Enum): + r"""Thumbnail preview alignment for standalone cards with + horizontal layout. + """ + THUMBNAIL_IMAGE_ALIGNMENT_UNSPECIFIED = 0 + LEFT = 1 + RIGHT = 2 + + card_orientation = proto.Field( + proto.ENUM, + number=1, + enum='Intent.Message.RbmStandaloneCard.CardOrientation', + ) + thumbnail_image_alignment = proto.Field( + proto.ENUM, + number=2, + enum='Intent.Message.RbmStandaloneCard.ThumbnailImageAlignment', + ) + card_content = proto.Field( + proto.MESSAGE, + number=3, + message='Intent.Message.RbmCardContent', + ) + + class RbmCardContent(proto.Message): + r"""Rich Business Messaging (RBM) Card content + + Attributes: + title (str): + Optional. Title of the card (at most 200 + bytes). + At least one of the title, description or media + must be set. + description (str): + Optional. Description of the card (at most + 2000 bytes). + At least one of the title, description or media + must be set. + media (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmCardContent.RbmMedia): + Optional. However at least one of the title, + description or media must be set. Media (image, + GIF or a video) to include in the card. + suggestions (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmSuggestion]): + Optional. List of suggestions to include in + the card. + """ + + class RbmMedia(proto.Message): + r"""Rich Business Messaging (RBM) Media displayed in Cards The following + media-types are currently supported: + + Image Types + + - image/jpeg + - image/jpg' + - image/gif + - image/png + + Video Types + + - video/h263 + - video/m4v + - video/mp4 + - video/mpeg + - video/mpeg4 + - video/webm + + Attributes: + file_uri (str): + Required. Publicly reachable URI of the file. + The RBM platform determines the MIME type of the + file from the content-type field in the HTTP + headers when the platform fetches the file. The + content-type field must be present and accurate + in the HTTP response from the URL. + thumbnail_uri (str): + Optional. Publicly reachable URI of the + thumbnail.If you don't provide a thumbnail URI, + the RBM platform displays a blank placeholder + thumbnail until the user's device downloads the + file. Depending on the user's setting, the file + may not download automatically and may require + the user to tap a download button. + height (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmCardContent.RbmMedia.Height): + Required for cards with vertical orientation. + The height of the media within a rich card with + a vertical layout. For a standalone card with + horizontal layout, height is not customizable, + and this field is ignored. + """ + class Height(proto.Enum): + r"""Media height""" + HEIGHT_UNSPECIFIED = 0 + SHORT = 1 + MEDIUM = 2 + TALL = 3 + + file_uri = proto.Field( + proto.STRING, + number=1, + ) + thumbnail_uri = proto.Field( + proto.STRING, + number=2, + ) + height = proto.Field( + proto.ENUM, + number=3, + enum='Intent.Message.RbmCardContent.RbmMedia.Height', + ) + + title = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + media = proto.Field( + proto.MESSAGE, + number=3, + message='Intent.Message.RbmCardContent.RbmMedia', + ) + suggestions = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Intent.Message.RbmSuggestion', + ) + + class RbmSuggestion(proto.Message): + r"""Rich Business Messaging (RBM) suggestion. Suggestions allow + user to easily select/click a predefined response or perform an + action (like opening a web uri). + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + reply (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmSuggestedReply): + Predefined replies for user to select instead + of typing + + This field is a member of `oneof`_ ``suggestion``. + action (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmSuggestedAction): + Predefined client side actions that user can + choose + + This field is a member of `oneof`_ ``suggestion``. + """ + + reply = proto.Field( + proto.MESSAGE, + number=1, + oneof='suggestion', + message='Intent.Message.RbmSuggestedReply', + ) + action = proto.Field( + proto.MESSAGE, + number=2, + oneof='suggestion', + message='Intent.Message.RbmSuggestedAction', + ) + + class RbmSuggestedReply(proto.Message): + r"""Rich Business Messaging (RBM) suggested reply that the user + can click instead of typing in their own response. + + Attributes: + text (str): + Suggested reply text. + postback_data (str): + Opaque payload that the Dialogflow receives + in a user event when the user taps the suggested + reply. This data will be also forwarded to + webhook to allow performing custom business + logic. + """ + + text = proto.Field( + proto.STRING, + number=1, + ) + postback_data = proto.Field( + proto.STRING, + number=2, + ) + + class RbmSuggestedAction(proto.Message): + r"""Rich Business Messaging (RBM) suggested client-side action + that the user can choose from the card. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + text (str): + Text to display alongside the action. + postback_data (str): + Opaque payload that the Dialogflow receives + in a user event when the user taps the suggested + action. This data will be also forwarded to + webhook to allow performing custom business + logic. + dial (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmSuggestedAction.RbmSuggestedActionDial): + Suggested client side action: Dial a phone + number + + This field is a member of `oneof`_ ``action``. + open_url (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmSuggestedAction.RbmSuggestedActionOpenUri): + Suggested client side action: Open a URI on + device + + This field is a member of `oneof`_ ``action``. + share_location (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmSuggestedAction.RbmSuggestedActionShareLocation): + Suggested client side action: Share user + location + + This field is a member of `oneof`_ ``action``. + """ + + class RbmSuggestedActionDial(proto.Message): + r"""Opens the user's default dialer app with the specified phone + number but does not dial automatically. + + Attributes: + phone_number (str): + Required. The phone number to fill in the default dialer + app. This field should be in + `E.164 `__ format. An + example of a correctly formatted phone number: +15556767888. + """ + + phone_number = proto.Field( + proto.STRING, + number=1, + ) + + class RbmSuggestedActionOpenUri(proto.Message): + r"""Opens the user's default web browser app to the specified uri + If the user has an app installed that is + registered as the default handler for the URL, then this app + will be opened instead, and its icon will be used in the + suggested action UI. + + Attributes: + uri (str): + Required. The uri to open on the user device + """ + + uri = proto.Field( + proto.STRING, + number=1, + ) + + class RbmSuggestedActionShareLocation(proto.Message): + r"""Opens the device's location chooser so the user can pick a + location to send back to the agent. + + """ + + text = proto.Field( + proto.STRING, + number=1, + ) + postback_data = proto.Field( + proto.STRING, + number=2, + ) + dial = proto.Field( + proto.MESSAGE, + number=3, + oneof='action', + message='Intent.Message.RbmSuggestedAction.RbmSuggestedActionDial', + ) + open_url = proto.Field( + proto.MESSAGE, + number=4, + oneof='action', + message='Intent.Message.RbmSuggestedAction.RbmSuggestedActionOpenUri', + ) + share_location = proto.Field( + proto.MESSAGE, + number=5, + oneof='action', + message='Intent.Message.RbmSuggestedAction.RbmSuggestedActionShareLocation', + ) + + class MediaContent(proto.Message): + r"""The media content card for Actions on Google. + + Attributes: + media_type (google.cloud.dialogflow_v2beta1.types.Intent.Message.MediaContent.ResponseMediaType): + Optional. What type of media is the content + (ie "audio"). + media_objects (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.MediaContent.ResponseMediaObject]): + Required. List of media objects. + """ + class ResponseMediaType(proto.Enum): + r"""Format of response media type.""" + RESPONSE_MEDIA_TYPE_UNSPECIFIED = 0 + AUDIO = 1 + + class ResponseMediaObject(proto.Message): + r"""Response media object for media content card. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Required. Name of media card. + description (str): + Optional. Description of media card. + large_image (google.cloud.dialogflow_v2beta1.types.Intent.Message.Image): + Optional. Image to display above media + content. + + This field is a member of `oneof`_ ``image``. + icon (google.cloud.dialogflow_v2beta1.types.Intent.Message.Image): + Optional. Icon to display above media + content. + + This field is a member of `oneof`_ ``image``. + content_url (str): + Required. Url where the media is stored. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + large_image = proto.Field( + proto.MESSAGE, + number=3, + oneof='image', + message='Intent.Message.Image', + ) + icon = proto.Field( + proto.MESSAGE, + number=4, + oneof='image', + message='Intent.Message.Image', + ) + content_url = proto.Field( + proto.STRING, + number=5, + ) + + media_type = proto.Field( + proto.ENUM, + number=1, + enum='Intent.Message.MediaContent.ResponseMediaType', + ) + media_objects = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Intent.Message.MediaContent.ResponseMediaObject', + ) + + class BrowseCarouselCard(proto.Message): + r"""Browse Carousel Card for Actions on Google. + https://developers.google.com/actions/assistant/responses#browsing_carousel + + Attributes: + items (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem]): + Required. List of items in the Browse + Carousel Card. Minimum of two items, maximum of + ten. + image_display_options (google.cloud.dialogflow_v2beta1.types.Intent.Message.BrowseCarouselCard.ImageDisplayOptions): + Optional. Settings for displaying the image. Applies to + every image in + [items][google.cloud.dialogflow.v2beta1.Intent.Message.BrowseCarouselCard.items]. + """ + class ImageDisplayOptions(proto.Enum): + r"""Image display options for Actions on Google. This should be + used for when the image's aspect ratio does not match the image + container's aspect ratio. + """ + IMAGE_DISPLAY_OPTIONS_UNSPECIFIED = 0 + GRAY = 1 + WHITE = 2 + CROPPED = 3 + BLURRED_BACKGROUND = 4 + + class BrowseCarouselCardItem(proto.Message): + r"""Browsing carousel tile + + Attributes: + open_uri_action (google.cloud.dialogflow_v2beta1.types.Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction): + Required. Action to present to the user. + title (str): + Required. Title of the carousel item. Maximum + of two lines of text. + description (str): + Optional. Description of the carousel item. + Maximum of four lines of text. + image (google.cloud.dialogflow_v2beta1.types.Intent.Message.Image): + Optional. Hero image for the carousel item. + footer (str): + Optional. Text that appears at the bottom of + the Browse Carousel Card. Maximum of one line of + text. + """ + + class OpenUrlAction(proto.Message): + r"""Actions on Google action to open a given url. + + Attributes: + url (str): + Required. URL + url_type_hint (google.cloud.dialogflow_v2beta1.types.Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction.UrlTypeHint): + Optional. Specifies the type of viewer that + is used when opening the URL. Defaults to + opening via web browser. + """ + class UrlTypeHint(proto.Enum): + r"""Type of the URI.""" + URL_TYPE_HINT_UNSPECIFIED = 0 + AMP_ACTION = 1 + AMP_CONTENT = 2 + + url = proto.Field( + proto.STRING, + number=1, + ) + url_type_hint = proto.Field( + proto.ENUM, + number=3, + enum='Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction.UrlTypeHint', + ) + + open_uri_action = proto.Field( + proto.MESSAGE, + number=1, + message='Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction', + ) + title = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + image = proto.Field( + proto.MESSAGE, + number=4, + message='Intent.Message.Image', + ) + footer = proto.Field( + proto.STRING, + number=5, + ) + + items = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem', + ) + image_display_options = proto.Field( + proto.ENUM, + number=2, + enum='Intent.Message.BrowseCarouselCard.ImageDisplayOptions', + ) + + class TableCard(proto.Message): + r"""Table card for Actions on Google. + + Attributes: + title (str): + Required. Title of the card. + subtitle (str): + Optional. Subtitle to the title. + image (google.cloud.dialogflow_v2beta1.types.Intent.Message.Image): + Optional. Image which should be displayed on + the card. + column_properties (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.ColumnProperties]): + Optional. Display properties for the columns + in this table. + rows (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.TableCardRow]): + Optional. Rows in this table of data. + buttons (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.BasicCard.Button]): + Optional. List of buttons for the card. + """ + + title = proto.Field( + proto.STRING, + number=1, + ) + subtitle = proto.Field( + proto.STRING, + number=2, + ) + image = proto.Field( + proto.MESSAGE, + number=3, + message='Intent.Message.Image', + ) + column_properties = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Intent.Message.ColumnProperties', + ) + rows = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='Intent.Message.TableCardRow', + ) + buttons = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='Intent.Message.BasicCard.Button', + ) + + class ColumnProperties(proto.Message): + r"""Column properties for + [TableCard][google.cloud.dialogflow.v2beta1.Intent.Message.TableCard]. + + Attributes: + header (str): + Required. Column heading. + horizontal_alignment (google.cloud.dialogflow_v2beta1.types.Intent.Message.ColumnProperties.HorizontalAlignment): + Optional. Defines text alignment for all + cells in this column. + """ + class HorizontalAlignment(proto.Enum): + r"""Text alignments within a cell.""" + HORIZONTAL_ALIGNMENT_UNSPECIFIED = 0 + LEADING = 1 + CENTER = 2 + TRAILING = 3 + + header = proto.Field( + proto.STRING, + number=1, + ) + horizontal_alignment = proto.Field( + proto.ENUM, + number=2, + enum='Intent.Message.ColumnProperties.HorizontalAlignment', + ) + + class TableCardRow(proto.Message): + r"""Row of + [TableCard][google.cloud.dialogflow.v2beta1.Intent.Message.TableCard]. + + Attributes: + cells (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.TableCardCell]): + Optional. List of cells that make up this + row. + divider_after (bool): + Optional. Whether to add a visual divider + after this row. + """ + + cells = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Intent.Message.TableCardCell', + ) + divider_after = proto.Field( + proto.BOOL, + number=2, + ) + + class TableCardCell(proto.Message): + r"""Cell of + [TableCardRow][google.cloud.dialogflow.v2beta1.Intent.Message.TableCardRow]. + + Attributes: + text (str): + Required. Text in this cell. + """ + + text = proto.Field( + proto.STRING, + number=1, + ) + + text = proto.Field( + proto.MESSAGE, + number=1, + oneof='message', + message='Intent.Message.Text', + ) + image = proto.Field( + proto.MESSAGE, + number=2, + oneof='message', + message='Intent.Message.Image', + ) + quick_replies = proto.Field( + proto.MESSAGE, + number=3, + oneof='message', + message='Intent.Message.QuickReplies', + ) + card = proto.Field( + proto.MESSAGE, + number=4, + oneof='message', + message='Intent.Message.Card', + ) + payload = proto.Field( + proto.MESSAGE, + number=5, + oneof='message', + message=struct_pb2.Struct, + ) + simple_responses = proto.Field( + proto.MESSAGE, + number=7, + oneof='message', + message='Intent.Message.SimpleResponses', + ) + basic_card = proto.Field( + proto.MESSAGE, + number=8, + oneof='message', + message='Intent.Message.BasicCard', + ) + suggestions = proto.Field( + proto.MESSAGE, + number=9, + oneof='message', + message='Intent.Message.Suggestions', + ) + link_out_suggestion = proto.Field( + proto.MESSAGE, + number=10, + oneof='message', + message='Intent.Message.LinkOutSuggestion', + ) + list_select = proto.Field( + proto.MESSAGE, + number=11, + oneof='message', + message='Intent.Message.ListSelect', + ) + carousel_select = proto.Field( + proto.MESSAGE, + number=12, + oneof='message', + message='Intent.Message.CarouselSelect', + ) + telephony_play_audio = proto.Field( + proto.MESSAGE, + number=13, + oneof='message', + message='Intent.Message.TelephonyPlayAudio', + ) + telephony_synthesize_speech = proto.Field( + proto.MESSAGE, + number=14, + oneof='message', + message='Intent.Message.TelephonySynthesizeSpeech', + ) + telephony_transfer_call = proto.Field( + proto.MESSAGE, + number=15, + oneof='message', + message='Intent.Message.TelephonyTransferCall', + ) + rbm_text = proto.Field( + proto.MESSAGE, + number=18, + oneof='message', + message='Intent.Message.RbmText', + ) + rbm_standalone_rich_card = proto.Field( + proto.MESSAGE, + number=19, + oneof='message', + message='Intent.Message.RbmStandaloneCard', + ) + rbm_carousel_rich_card = proto.Field( + proto.MESSAGE, + number=20, + oneof='message', + message='Intent.Message.RbmCarouselCard', + ) + browse_carousel_card = proto.Field( + proto.MESSAGE, + number=22, + oneof='message', + message='Intent.Message.BrowseCarouselCard', + ) + table_card = proto.Field( + proto.MESSAGE, + number=23, + oneof='message', + message='Intent.Message.TableCard', + ) + media_content = proto.Field( + proto.MESSAGE, + number=24, + oneof='message', + message='Intent.Message.MediaContent', + ) + platform = proto.Field( + proto.ENUM, + number=6, + enum='Intent.Message.Platform', + ) + + class FollowupIntentInfo(proto.Message): + r"""Represents a single followup intent in the chain. + + Attributes: + followup_intent_name (str): + The unique identifier of the followup intent. Format: + ``projects//agent/intents/``. + parent_followup_intent_name (str): + The unique identifier of the followup intent's parent. + Format: ``projects//agent/intents/``. + """ + + followup_intent_name = proto.Field( + proto.STRING, + number=1, + ) + parent_followup_intent_name = proto.Field( + proto.STRING, + number=2, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + webhook_state = proto.Field( + proto.ENUM, + number=6, + enum=WebhookState, + ) + priority = proto.Field( + proto.INT32, + number=3, + ) + is_fallback = proto.Field( + proto.BOOL, + number=4, + ) + ml_enabled = proto.Field( + proto.BOOL, + number=5, + ) + ml_disabled = proto.Field( + proto.BOOL, + number=19, + ) + live_agent_handoff = proto.Field( + proto.BOOL, + number=20, + ) + end_interaction = proto.Field( + proto.BOOL, + number=21, + ) + input_context_names = proto.RepeatedField( + proto.STRING, + number=7, + ) + events = proto.RepeatedField( + proto.STRING, + number=8, + ) + training_phrases = proto.RepeatedField( + proto.MESSAGE, + number=9, + message=TrainingPhrase, + ) + action = proto.Field( + proto.STRING, + number=10, + ) + output_contexts = proto.RepeatedField( + proto.MESSAGE, + number=11, + message=context.Context, + ) + reset_contexts = proto.Field( + proto.BOOL, + number=12, + ) + parameters = proto.RepeatedField( + proto.MESSAGE, + number=13, + message=Parameter, + ) + messages = proto.RepeatedField( + proto.MESSAGE, + number=14, + message=Message, + ) + default_response_platforms = proto.RepeatedField( + proto.ENUM, + number=15, + enum=Message.Platform, + ) + root_followup_intent_name = proto.Field( + proto.STRING, + number=16, + ) + parent_followup_intent_name = proto.Field( + proto.STRING, + number=17, + ) + followup_intent_info = proto.RepeatedField( + proto.MESSAGE, + number=18, + message=FollowupIntentInfo, + ) + + +class ListIntentsRequest(proto.Message): + r"""The request message for + [Intents.ListIntents][google.cloud.dialogflow.v2beta1.Intents.ListIntents]. + + Attributes: + parent (str): + Required. The agent to list all intents from. Format: + ``projects//agent`` or + ``projects//locations//agent``. + + Alternatively, you can specify the environment to list + intents for. Format: + ``projects//agent/environments/`` + or + ``projects//locations//agent/environments/``. + Note: training phrases of the intents will not be returned + for non-draft environment. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + intent_view (google.cloud.dialogflow_v2beta1.types.IntentView): + Optional. The resource view to apply to the + returned intent. + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + intent_view = proto.Field( + proto.ENUM, + number=3, + enum='IntentView', + ) + page_size = proto.Field( + proto.INT32, + number=4, + ) + page_token = proto.Field( + proto.STRING, + number=5, + ) + + +class ListIntentsResponse(proto.Message): + r"""The response message for + [Intents.ListIntents][google.cloud.dialogflow.v2beta1.Intents.ListIntents]. + + Attributes: + intents (Sequence[google.cloud.dialogflow_v2beta1.types.Intent]): + The list of agent intents. There will be a maximum number of + items returned based on the page_size field in the request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + intents = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Intent', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetIntentRequest(proto.Message): + r"""The request message for + [Intents.GetIntent][google.cloud.dialogflow.v2beta1.Intents.GetIntent]. + + Attributes: + name (str): + Required. The name of the intent. Supported formats: + + - ``projects//agent/intents/`` + - ``projects//locations//agent/intents/`` + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + intent_view (google.cloud.dialogflow_v2beta1.types.IntentView): + Optional. The resource view to apply to the + returned intent. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + intent_view = proto.Field( + proto.ENUM, + number=3, + enum='IntentView', + ) + + +class CreateIntentRequest(proto.Message): + r"""The request message for + [Intents.CreateIntent][google.cloud.dialogflow.v2beta1.Intents.CreateIntent]. + + Attributes: + parent (str): + Required. The agent to create a intent for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + intent (google.cloud.dialogflow_v2beta1.types.Intent): + Required. The intent to create. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + intent_view (google.cloud.dialogflow_v2beta1.types.IntentView): + Optional. The resource view to apply to the + returned intent. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + intent = proto.Field( + proto.MESSAGE, + number=2, + message='Intent', + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + intent_view = proto.Field( + proto.ENUM, + number=4, + enum='IntentView', + ) + + +class UpdateIntentRequest(proto.Message): + r"""The request message for + [Intents.UpdateIntent][google.cloud.dialogflow.v2beta1.Intents.UpdateIntent]. + + Attributes: + intent (google.cloud.dialogflow_v2beta1.types.Intent): + Required. The intent to update. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which fields + get updated. + intent_view (google.cloud.dialogflow_v2beta1.types.IntentView): + Optional. The resource view to apply to the + returned intent. + """ + + intent = proto.Field( + proto.MESSAGE, + number=1, + message='Intent', + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + intent_view = proto.Field( + proto.ENUM, + number=4, + enum='IntentView', + ) + + +class DeleteIntentRequest(proto.Message): + r"""The request message for + [Intents.DeleteIntent][google.cloud.dialogflow.v2beta1.Intents.DeleteIntent]. + + Attributes: + name (str): + Required. The name of the intent to delete. If this intent + has direct or indirect followup intents, we also delete + them. + + Supported formats: + + - ``projects//agent/intents/`` + - ``projects//locations//agent/intents/`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class BatchUpdateIntentsRequest(proto.Message): + r"""The request message for + [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2beta1.Intents.BatchUpdateIntents]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The name of the agent to update or create intents + in. Supported formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + intent_batch_uri (str): + The URI to a Google Cloud Storage file + containing intents to update or create. The file + format can either be a serialized proto (of + IntentBatch type) or JSON object. Note: The URI + must start with "gs://". + + This field is a member of `oneof`_ ``intent_batch``. + intent_batch_inline (google.cloud.dialogflow_v2beta1.types.IntentBatch): + The collection of intents to update or + create. + + This field is a member of `oneof`_ ``intent_batch``. + language_code (str): + Optional. The language used to access language-specific + data. If not specified, the agent's default language is + used. For more information, see `Multilingual intent and + entity + data `__. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which fields + get updated. + intent_view (google.cloud.dialogflow_v2beta1.types.IntentView): + Optional. The resource view to apply to the + returned intent. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + intent_batch_uri = proto.Field( + proto.STRING, + number=2, + oneof='intent_batch', + ) + intent_batch_inline = proto.Field( + proto.MESSAGE, + number=3, + oneof='intent_batch', + message='IntentBatch', + ) + language_code = proto.Field( + proto.STRING, + number=4, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + intent_view = proto.Field( + proto.ENUM, + number=6, + enum='IntentView', + ) + + +class BatchUpdateIntentsResponse(proto.Message): + r"""The response message for + [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2beta1.Intents.BatchUpdateIntents]. + + Attributes: + intents (Sequence[google.cloud.dialogflow_v2beta1.types.Intent]): + The collection of updated or created intents. + """ + + intents = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Intent', + ) + + +class BatchDeleteIntentsRequest(proto.Message): + r"""The request message for + [Intents.BatchDeleteIntents][google.cloud.dialogflow.v2beta1.Intents.BatchDeleteIntents]. + + Attributes: + parent (str): + Required. The name of the agent to delete all entities types + for. Supported formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + intents (Sequence[google.cloud.dialogflow_v2beta1.types.Intent]): + Required. The collection of intents to delete. Only intent + ``name`` must be filled in. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + intents = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Intent', + ) + + +class IntentBatch(proto.Message): + r"""This message is a wrapper around a collection of intents. + + Attributes: + intents (Sequence[google.cloud.dialogflow_v2beta1.types.Intent]): + A collection of intents. + """ + + intents = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Intent', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/knowledge_base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/knowledge_base.py new file mode 100644 index 000000000..dca009b2d --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/knowledge_base.py @@ -0,0 +1,257 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2beta1', + manifest={ + 'KnowledgeBase', + 'ListKnowledgeBasesRequest', + 'ListKnowledgeBasesResponse', + 'GetKnowledgeBaseRequest', + 'CreateKnowledgeBaseRequest', + 'DeleteKnowledgeBaseRequest', + 'UpdateKnowledgeBaseRequest', + }, +) + + +class KnowledgeBase(proto.Message): + r"""A knowledge base represents a collection of knowledge documents that + you provide to Dialogflow. Your knowledge documents contain + information that may be useful during conversations with end-users. + Some Dialogflow features use knowledge bases when looking for a + response to an end-user input. + + For more information, see the `knowledge base + guide `__. + + Note: The ``projects.agent.knowledgeBases`` resource is deprecated; + only use ``projects.knowledgeBases``. + + Attributes: + name (str): + The knowledge base resource name. The name must be empty + when creating a knowledge base. Format: + ``projects//locations//knowledgeBases/``. + display_name (str): + Required. The display name of the knowledge + base. The name must be 1024 bytes or less; + otherwise, the creation request fails. + language_code (str): + Language which represents the KnowledgeBase. + When the KnowledgeBase is created/updated, this + is populated for all non en-us languages. If not + populated, the default language en-us applies. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + language_code = proto.Field( + proto.STRING, + number=4, + ) + + +class ListKnowledgeBasesRequest(proto.Message): + r"""Request message for + [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2beta1.KnowledgeBases.ListKnowledgeBases]. + + Attributes: + parent (str): + Required. The project to list of knowledge bases for. + Format: ``projects//locations/``. + page_size (int): + The maximum number of items to return in a + single page. By default 10 and at most 100. + page_token (str): + The next_page_token value returned from a previous list + request. + filter (str): + The filter expression used to filter knowledge bases + returned by the list method. The expression has the + following syntax: + + [AND ] ... + + The following fields and operators are supported: + + - display_name with has(:) operator + - language_code with equals(=) operator + + Examples: + + - 'language_code=en-us' matches knowledge bases with en-us + language code. + - 'display_name:articles' matches knowledge bases whose + display name contains "articles". + - 'display_name:"Best Articles"' matches knowledge bases + whose display name contains "Best Articles". + - 'language_code=en-gb AND display_name=articles' matches + all knowledge bases whose display name contains + "articles" and whose language code is "en-gb". + + Note: An empty filter string (i.e. "") is a no-op and will + result in no filtering. + + For more information about filtering, see `API + Filtering `__. + """ + + 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 ListKnowledgeBasesResponse(proto.Message): + r"""Response message for + [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2beta1.KnowledgeBases.ListKnowledgeBases]. + + Attributes: + knowledge_bases (Sequence[google.cloud.dialogflow_v2beta1.types.KnowledgeBase]): + The list of knowledge bases. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + knowledge_bases = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='KnowledgeBase', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetKnowledgeBaseRequest(proto.Message): + r"""Request message for + [KnowledgeBases.GetKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.GetKnowledgeBase]. + + Attributes: + name (str): + Required. The name of the knowledge base to retrieve. Format + ``projects//locations//knowledgeBases/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateKnowledgeBaseRequest(proto.Message): + r"""Request message for + [KnowledgeBases.CreateKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.CreateKnowledgeBase]. + + Attributes: + parent (str): + Required. The project to create a knowledge base for. + Format: ``projects//locations/``. + knowledge_base (google.cloud.dialogflow_v2beta1.types.KnowledgeBase): + Required. The knowledge base to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + knowledge_base = proto.Field( + proto.MESSAGE, + number=2, + message='KnowledgeBase', + ) + + +class DeleteKnowledgeBaseRequest(proto.Message): + r"""Request message for + [KnowledgeBases.DeleteKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.DeleteKnowledgeBase]. + + Attributes: + name (str): + Required. The name of the knowledge base to delete. Format: + ``projects//locations//knowledgeBases/``. + force (bool): + Optional. Force deletes the knowledge base. + When set to true, any documents in the knowledge + base are also deleted. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + force = proto.Field( + proto.BOOL, + number=2, + ) + + +class UpdateKnowledgeBaseRequest(proto.Message): + r"""Request message for + [KnowledgeBases.UpdateKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.UpdateKnowledgeBase]. + + Attributes: + knowledge_base (google.cloud.dialogflow_v2beta1.types.KnowledgeBase): + Required. The knowledge base to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Not specified means ``update all``. Currently, + only ``display_name`` can be updated, an InvalidArgument + will be returned for attempting to update other fields. + """ + + knowledge_base = proto.Field( + proto.MESSAGE, + number=1, + message='KnowledgeBase', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/participant.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/participant.py new file mode 100644 index 000000000..5e57e4814 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/participant.py @@ -0,0 +1,1712 @@ +# -*- 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.dialogflow_v2beta1.types import audio_config +from google.cloud.dialogflow_v2beta1.types import session +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2beta1', + manifest={ + 'Participant', + 'Message', + 'CreateParticipantRequest', + 'GetParticipantRequest', + 'ListParticipantsRequest', + 'ListParticipantsResponse', + 'UpdateParticipantRequest', + 'OutputAudio', + 'AutomatedAgentReply', + 'SuggestionFeature', + 'AssistQueryParameters', + 'AnalyzeContentRequest', + 'DtmfParameters', + 'AnalyzeContentResponse', + 'AnnotatedMessagePart', + 'MessageAnnotation', + 'ArticleAnswer', + 'FaqAnswer', + 'SmartReplyAnswer', + 'SuggestionResult', + 'SuggestArticlesRequest', + 'SuggestArticlesResponse', + 'SuggestFaqAnswersRequest', + 'SuggestFaqAnswersResponse', + 'SuggestSmartRepliesRequest', + 'SuggestSmartRepliesResponse', + 'Suggestion', + 'ListSuggestionsRequest', + 'ListSuggestionsResponse', + 'CompileSuggestionRequest', + 'CompileSuggestionResponse', + 'ResponseMessage', + }, +) + + +class Participant(proto.Message): + r"""Represents a conversation participant (human agent, virtual + agent, end-user). + + Attributes: + name (str): + Optional. The unique identifier of this participant. Format: + ``projects//locations//conversations//participants/``. + role (google.cloud.dialogflow_v2beta1.types.Participant.Role): + Immutable. The role this participant plays in + the conversation. This field must be set during + participant creation and is then immutable. + obfuscated_external_user_id (str): + Optional. Obfuscated user id that should be associated with + the created participant. + + You can specify a user id as follows: + + 1. If you set this field in + [CreateParticipantRequest][google.cloud.dialogflow.v2beta1.CreateParticipantRequest.participant] + or + [UpdateParticipantRequest][google.cloud.dialogflow.v2beta1.UpdateParticipantRequest.participant], + Dialogflow adds the obfuscated user id with the + participant. + + 2. If you set this field in + [AnalyzeContent][google.cloud.dialogflow.v2beta1.AnalyzeContentRequest.obfuscated_external_user_id] + or + [StreamingAnalyzeContent][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.obfuscated_external_user_id], + Dialogflow will update + [Participant.obfuscated_external_user_id][google.cloud.dialogflow.v2beta1.Participant.obfuscated_external_user_id]. + + Dialogflow uses this user id for following purposes: + + 1) Billing and measurement. If user with the same + obfuscated_external_user_id is created in a later + conversation, dialogflow will know it's the same user. 2) + Agent assist suggestion personalization. For example, + Dialogflow can use it to provide personalized smart reply + suggestions for this user. + + Note: + + - Please never pass raw user ids to Dialogflow. Always + obfuscate your user id first. + - Dialogflow only accepts a UTF-8 encoded string, e.g., a + hex digest of a hash function like SHA-512. + - The length of the user id must be <= 256 characters. + documents_metadata_filters (Sequence[google.cloud.dialogflow_v2beta1.types.Participant.DocumentsMetadataFiltersEntry]): + Optional. Key-value filters on the metadata of documents + returned by article suggestion. If specified, article + suggestion only returns suggested documents that match all + filters in their + [Document.metadata][google.cloud.dialogflow.v2beta1.Document.metadata]. + Multiple values for a metadata key should be concatenated by + comma. For example, filters to match all documents that have + 'US' or 'CA' in their market metadata values and 'agent' in + their user metadata values will be + + :: + + documents_metadata_filters { + key: "market" + value: "US,CA" + } + documents_metadata_filters { + key: "user" + value: "agent" + } + """ + class Role(proto.Enum): + r"""Enumeration of the roles a participant can play in a + conversation. + """ + ROLE_UNSPECIFIED = 0 + HUMAN_AGENT = 1 + AUTOMATED_AGENT = 2 + END_USER = 3 + + name = proto.Field( + proto.STRING, + number=1, + ) + role = proto.Field( + proto.ENUM, + number=2, + enum=Role, + ) + obfuscated_external_user_id = proto.Field( + proto.STRING, + number=7, + ) + documents_metadata_filters = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + + +class Message(proto.Message): + r"""Represents a message posted into a conversation. + + Attributes: + name (str): + Optional. The unique identifier of the message. Format: + ``projects//locations//conversations//messages/``. + content (str): + Required. The message content. + language_code (str): + Optional. The message language. This should be a + `BCP-47 `__ + language tag. Example: "en-US". + participant (str): + Output only. The participant that sends this + message. + participant_role (google.cloud.dialogflow_v2beta1.types.Participant.Role): + Output only. The role of the participant. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the message was + created in Contact Center AI. + send_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The time when the message was sent. + message_annotation (google.cloud.dialogflow_v2beta1.types.MessageAnnotation): + Output only. The annotation for the message. + sentiment_analysis (google.cloud.dialogflow_v2beta1.types.SentimentAnalysisResult): + Output only. The sentiment analysis result + for the message. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + content = proto.Field( + proto.STRING, + number=2, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + participant = proto.Field( + proto.STRING, + number=4, + ) + participant_role = proto.Field( + proto.ENUM, + number=5, + enum='Participant.Role', + ) + create_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + send_time = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + message_annotation = proto.Field( + proto.MESSAGE, + number=7, + message='MessageAnnotation', + ) + sentiment_analysis = proto.Field( + proto.MESSAGE, + number=8, + message=session.SentimentAnalysisResult, + ) + + +class CreateParticipantRequest(proto.Message): + r"""The request message for + [Participants.CreateParticipant][google.cloud.dialogflow.v2beta1.Participants.CreateParticipant]. + + Attributes: + parent (str): + Required. Resource identifier of the conversation adding the + participant. Format: + ``projects//locations//conversations/``. + participant (google.cloud.dialogflow_v2beta1.types.Participant): + Required. The participant to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + participant = proto.Field( + proto.MESSAGE, + number=2, + message='Participant', + ) + + +class GetParticipantRequest(proto.Message): + r"""The request message for + [Participants.GetParticipant][google.cloud.dialogflow.v2beta1.Participants.GetParticipant]. + + Attributes: + name (str): + Required. The name of the participant. Format: + ``projects//locations//conversations//participants/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListParticipantsRequest(proto.Message): + r"""The request message for + [Participants.ListParticipants][google.cloud.dialogflow.v2beta1.Participants.ListParticipants]. + + Attributes: + parent (str): + Required. The conversation to list all participants from. + Format: + ``projects//locations//conversations/``. + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListParticipantsResponse(proto.Message): + r"""The response message for + [Participants.ListParticipants][google.cloud.dialogflow.v2beta1.Participants.ListParticipants]. + + Attributes: + participants (Sequence[google.cloud.dialogflow_v2beta1.types.Participant]): + The list of participants. There is a maximum number of items + returned based on the page_size field in the request. + next_page_token (str): + Token to retrieve the next page of results or + empty if there are no more results in the list. + """ + + @property + def raw_page(self): + return self + + participants = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Participant', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateParticipantRequest(proto.Message): + r"""The request message for + [Participants.UpdateParticipant][google.cloud.dialogflow.v2beta1.Participants.UpdateParticipant]. + + Attributes: + participant (google.cloud.dialogflow_v2beta1.types.Participant): + Required. The participant to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to specify which fields to + update. + """ + + participant = proto.Field( + proto.MESSAGE, + number=1, + message='Participant', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class OutputAudio(proto.Message): + r"""Represents the natural language speech audio to be played to + the end user. + + Attributes: + config (google.cloud.dialogflow_v2beta1.types.OutputAudioConfig): + Required. Instructs the speech synthesizer + how to generate the speech audio. + audio (bytes): + Required. The natural language speech audio. + """ + + config = proto.Field( + proto.MESSAGE, + number=1, + message=audio_config.OutputAudioConfig, + ) + audio = proto.Field( + proto.BYTES, + number=2, + ) + + +class AutomatedAgentReply(proto.Message): + r"""Represents a response from an automated agent. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + detect_intent_response (google.cloud.dialogflow_v2beta1.types.DetectIntentResponse): + Response of the Dialogflow + [Sessions.DetectIntent][google.cloud.dialogflow.v2beta1.Sessions.DetectIntent] + call. + + This field is a member of `oneof`_ ``response``. + response_messages (Sequence[google.cloud.dialogflow_v2beta1.types.ResponseMessage]): + Response messages from the automated agent. + intent (str): + Name of the intent if an intent is matched for the query. + For a V2 query, the value format is + ``projects//locations/ /agent/intents/``. + For a V3 query, the value format is + ``projects//locations/ /agents//intents/``. + + This field is a member of `oneof`_ ``match``. + event (str): + Event name if an event is triggered for the + query. + + This field is a member of `oneof`_ ``match``. + match_confidence (float): + The confidence of the match. Values range + from 0.0 (completely uncertain) to 1.0 + (completely certain). This value is for + informational purpose only and is only used to + help match the best intent within the + classification threshold. This value may change + for the same end-user expression at any time due + to a model retraining or change in + implementation. + parameters (google.protobuf.struct_pb2.Struct): + The collection of current parameters at the + time of this response. + cx_session_parameters (google.protobuf.struct_pb2.Struct): + The collection of current Dialogflow CX agent session + parameters at the time of this response. Deprecated: Use + ``parameters`` instead. + automated_agent_reply_type (google.cloud.dialogflow_v2beta1.types.AutomatedAgentReply.AutomatedAgentReplyType): + AutomatedAgentReply type. + allow_cancellation (bool): + Indicates whether the partial automated agent + reply is interruptible when a later reply + message arrives. e.g. if the agent specified + some music as partial response, it can be + cancelled. + """ + class AutomatedAgentReplyType(proto.Enum): + r"""Represents different automated agent reply types.""" + AUTOMATED_AGENT_REPLY_TYPE_UNSPECIFIED = 0 + PARTIAL = 1 + FINAL = 2 + + detect_intent_response = proto.Field( + proto.MESSAGE, + number=1, + oneof='response', + message=session.DetectIntentResponse, + ) + response_messages = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='ResponseMessage', + ) + intent = proto.Field( + proto.STRING, + number=4, + oneof='match', + ) + event = proto.Field( + proto.STRING, + number=5, + oneof='match', + ) + match_confidence = proto.Field( + proto.FLOAT, + number=9, + ) + parameters = proto.Field( + proto.MESSAGE, + number=10, + message=struct_pb2.Struct, + ) + cx_session_parameters = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + automated_agent_reply_type = proto.Field( + proto.ENUM, + number=7, + enum=AutomatedAgentReplyType, + ) + allow_cancellation = proto.Field( + proto.BOOL, + number=8, + ) + + +class SuggestionFeature(proto.Message): + r"""The type of Human Agent Assistant API suggestion to perform, and the + maximum number of results to return for that type. Multiple + ``Feature`` objects can be specified in the ``features`` list. + + Attributes: + type_ (google.cloud.dialogflow_v2beta1.types.SuggestionFeature.Type): + Type of Human Agent Assistant API feature to + request. + """ + class Type(proto.Enum): + r"""Defines the type of Human Agent Assistant feature.""" + TYPE_UNSPECIFIED = 0 + ARTICLE_SUGGESTION = 1 + FAQ = 2 + SMART_REPLY = 3 + + type_ = proto.Field( + proto.ENUM, + number=1, + enum=Type, + ) + + +class AssistQueryParameters(proto.Message): + r"""Represents the parameters of human assist query. + + Attributes: + documents_metadata_filters (Sequence[google.cloud.dialogflow_v2beta1.types.AssistQueryParameters.DocumentsMetadataFiltersEntry]): + Key-value filters on the metadata of documents returned by + article suggestion. If specified, article suggestion only + returns suggested documents that match all filters in their + [Document.metadata][google.cloud.dialogflow.v2beta1.Document.metadata]. + Multiple values for a metadata key should be concatenated by + comma. For example, filters to match all documents that have + 'US' or 'CA' in their market metadata values and 'agent' in + their user metadata values will be + + :: + + documents_metadata_filters { + key: "market" + value: "US,CA" + } + documents_metadata_filters { + key: "user" + value: "agent" + } + """ + + documents_metadata_filters = proto.MapField( + proto.STRING, + proto.STRING, + number=1, + ) + + +class AnalyzeContentRequest(proto.Message): + r"""The request message for + [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + participant (str): + Required. The name of the participant this text comes from. + Format: + ``projects//locations//conversations//participants/``. + text_input (google.cloud.dialogflow_v2beta1.types.TextInput): + The natural language text to be processed. + + This field is a member of `oneof`_ ``input``. + event_input (google.cloud.dialogflow_v2beta1.types.EventInput): + An input event to send to Dialogflow. + + This field is a member of `oneof`_ ``input``. + reply_audio_config (google.cloud.dialogflow_v2beta1.types.OutputAudioConfig): + Speech synthesis configuration. + The speech synthesis settings for a virtual + agent that may be configured for the associated + conversation profile are not used when calling + AnalyzeContent. If this configuration is not + supplied, speech synthesis is disabled. + query_params (google.cloud.dialogflow_v2beta1.types.QueryParameters): + Parameters for a Dialogflow virtual-agent + query. + assist_query_params (google.cloud.dialogflow_v2beta1.types.AssistQueryParameters): + Parameters for a human assist query. + message_send_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The send time of the message from + end user or human agent's perspective. It is + used for identifying the same message under one + participant. + + Given two messages under the same participant: + - If send time are different regardless of + whether the content of the messages are exactly + the same, the conversation will regard them as + two distinct messages sent by the participant. + - If send time is the same regardless of whether + the content of the messages are exactly the + same, the conversation will regard them as same + message, and ignore the message received later. + If the value is not provided, a new request will + always be regarded as a new message without any + de-duplication. + request_id (str): + A unique identifier for this request. Restricted to 36 ASCII + characters. A random UUID is recommended. This request is + only idempotent if a ``request_id`` is provided. + """ + + participant = proto.Field( + proto.STRING, + number=1, + ) + text_input = proto.Field( + proto.MESSAGE, + number=6, + oneof='input', + message=session.TextInput, + ) + event_input = proto.Field( + proto.MESSAGE, + number=8, + oneof='input', + message=session.EventInput, + ) + reply_audio_config = proto.Field( + proto.MESSAGE, + number=5, + message=audio_config.OutputAudioConfig, + ) + query_params = proto.Field( + proto.MESSAGE, + number=9, + message=session.QueryParameters, + ) + assist_query_params = proto.Field( + proto.MESSAGE, + number=14, + message='AssistQueryParameters', + ) + message_send_time = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + request_id = proto.Field( + proto.STRING, + number=11, + ) + + +class DtmfParameters(proto.Message): + r"""The message in the response that indicates the parameters of + DTMF. + + Attributes: + accepts_dtmf_input (bool): + Indicates whether DTMF input can be handled + in the next request. + """ + + accepts_dtmf_input = proto.Field( + proto.BOOL, + number=1, + ) + + +class AnalyzeContentResponse(proto.Message): + r"""The response message for + [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent]. + + Attributes: + reply_text (str): + Output only. The output text content. + This field is set if the automated agent + responded with text to show to the user. + reply_audio (google.cloud.dialogflow_v2beta1.types.OutputAudio): + Optional. The audio data bytes encoded as specified in the + request. This field is set if: + + - ``reply_audio_config`` was specified in the request, or + - The automated agent responded with audio to play to the + user. In such case, ``reply_audio.config`` contains + settings used to synthesize the speech. + + In some scenarios, multiple output audio fields may be + present in the response structure. In these cases, only the + top-most-level audio output has content. + automated_agent_reply (google.cloud.dialogflow_v2beta1.types.AutomatedAgentReply): + Optional. Only set if a Dialogflow automated agent has + responded. Note that: + [AutomatedAgentReply.detect_intent_response.output_audio][] + and + [AutomatedAgentReply.detect_intent_response.output_audio_config][] + are always empty, use + [reply_audio][google.cloud.dialogflow.v2beta1.AnalyzeContentResponse.reply_audio] + instead. + message (google.cloud.dialogflow_v2beta1.types.Message): + Output only. Message analyzed by CCAI. + human_agent_suggestion_results (Sequence[google.cloud.dialogflow_v2beta1.types.SuggestionResult]): + The suggestions for most recent human agent. The order is + the same as + [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] + of + [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.human_agent_suggestion_config]. + end_user_suggestion_results (Sequence[google.cloud.dialogflow_v2beta1.types.SuggestionResult]): + The suggestions for end user. The order is the same as + [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] + of + [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.end_user_suggestion_config]. + dtmf_parameters (google.cloud.dialogflow_v2beta1.types.DtmfParameters): + Indicates the parameters of DTMF. + """ + + reply_text = proto.Field( + proto.STRING, + number=1, + ) + reply_audio = proto.Field( + proto.MESSAGE, + number=2, + message='OutputAudio', + ) + automated_agent_reply = proto.Field( + proto.MESSAGE, + number=3, + message='AutomatedAgentReply', + ) + message = proto.Field( + proto.MESSAGE, + number=5, + message='Message', + ) + human_agent_suggestion_results = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='SuggestionResult', + ) + end_user_suggestion_results = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='SuggestionResult', + ) + dtmf_parameters = proto.Field( + proto.MESSAGE, + number=9, + message='DtmfParameters', + ) + + +class AnnotatedMessagePart(proto.Message): + r"""Represents a part of a message possibly annotated with an + entity. The part can be an entity or purely a part of the + message between two entities or message start/end. + + Attributes: + text (str): + Required. A part of a message possibly + annotated with an entity. + entity_type (str): + Optional. The `Dialogflow system entity + type `__ + of this message part. If this is empty, Dialogflow could not + annotate the phrase part with a system entity. + formatted_value (google.protobuf.struct_pb2.Value): + Optional. The `Dialogflow system entity formatted + value `__ + of this message part. For example for a system entity of + type ``@sys.unit-currency``, this may contain: + + .. raw:: html + +
+                {
+                  "amount": 5,
+                  "currency": "USD"
+                }
+                
+ """ + + text = proto.Field( + proto.STRING, + number=1, + ) + entity_type = proto.Field( + proto.STRING, + number=2, + ) + formatted_value = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Value, + ) + + +class MessageAnnotation(proto.Message): + r"""Represents the result of annotation for the message. + + Attributes: + parts (Sequence[google.cloud.dialogflow_v2beta1.types.AnnotatedMessagePart]): + Optional. The collection of annotated message parts ordered + by their position in the message. You can recover the + annotated message by concatenating + [AnnotatedMessagePart.text]. + contain_entities (bool): + Required. Indicates whether the text message + contains entities. + """ + + parts = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AnnotatedMessagePart', + ) + contain_entities = proto.Field( + proto.BOOL, + number=2, + ) + + +class ArticleAnswer(proto.Message): + r"""Represents article answer. + + Attributes: + title (str): + The article title. + uri (str): + The article URI. + snippets (Sequence[str]): + Output only. Article snippets. + metadata (Sequence[google.cloud.dialogflow_v2beta1.types.ArticleAnswer.MetadataEntry]): + A map that contains metadata about the answer + and the document from which it originates. + answer_record (str): + The name of answer record, in the format of + "projects//locations//answerRecords/". + """ + + title = proto.Field( + proto.STRING, + number=1, + ) + uri = proto.Field( + proto.STRING, + number=2, + ) + snippets = proto.RepeatedField( + proto.STRING, + number=3, + ) + metadata = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + answer_record = proto.Field( + proto.STRING, + number=6, + ) + + +class FaqAnswer(proto.Message): + r"""Represents answer from "frequently asked questions". + + Attributes: + answer (str): + The piece of text from the ``source`` knowledge base + document. + confidence (float): + The system's confidence score that this + Knowledge answer is a good match for this + conversational query, range from 0.0 (completely + uncertain) to 1.0 (completely certain). + question (str): + The corresponding FAQ question. + source (str): + Indicates which Knowledge Document this answer was extracted + from. Format: + ``projects//locations//agent/knowledgeBases//documents/``. + metadata (Sequence[google.cloud.dialogflow_v2beta1.types.FaqAnswer.MetadataEntry]): + A map that contains metadata about the answer + and the document from which it originates. + answer_record (str): + The name of answer record, in the format of + "projects//locations//answerRecords/". + """ + + answer = proto.Field( + proto.STRING, + number=1, + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + question = proto.Field( + proto.STRING, + number=3, + ) + source = proto.Field( + proto.STRING, + number=4, + ) + metadata = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + answer_record = proto.Field( + proto.STRING, + number=6, + ) + + +class SmartReplyAnswer(proto.Message): + r"""Represents a smart reply answer. + + Attributes: + reply (str): + The content of the reply. + confidence (float): + Smart reply confidence. + The system's confidence score that this reply is + a good match for this conversation, as a value + from 0.0 (completely uncertain) to 1.0 + (completely certain). + answer_record (str): + The name of answer record, in the format of + "projects//locations//answerRecords/". + """ + + reply = proto.Field( + proto.STRING, + number=1, + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + answer_record = proto.Field( + proto.STRING, + number=3, + ) + + +class SuggestionResult(proto.Message): + r"""One response of different type of suggestion response which is used + in the response of + [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent] + and + [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent], + as well as + [HumanAgentAssistantEvent][google.cloud.dialogflow.v2beta1.HumanAgentAssistantEvent]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + error (google.rpc.status_pb2.Status): + Error status if the request failed. + + This field is a member of `oneof`_ ``suggestion_response``. + suggest_articles_response (google.cloud.dialogflow_v2beta1.types.SuggestArticlesResponse): + SuggestArticlesResponse if request is for + ARTICLE_SUGGESTION. + + This field is a member of `oneof`_ ``suggestion_response``. + suggest_faq_answers_response (google.cloud.dialogflow_v2beta1.types.SuggestFaqAnswersResponse): + SuggestFaqAnswersResponse if request is for FAQ_ANSWER. + + This field is a member of `oneof`_ ``suggestion_response``. + suggest_smart_replies_response (google.cloud.dialogflow_v2beta1.types.SuggestSmartRepliesResponse): + SuggestSmartRepliesResponse if request is for SMART_REPLY. + + This field is a member of `oneof`_ ``suggestion_response``. + """ + + error = proto.Field( + proto.MESSAGE, + number=1, + oneof='suggestion_response', + message=status_pb2.Status, + ) + suggest_articles_response = proto.Field( + proto.MESSAGE, + number=2, + oneof='suggestion_response', + message='SuggestArticlesResponse', + ) + suggest_faq_answers_response = proto.Field( + proto.MESSAGE, + number=3, + oneof='suggestion_response', + message='SuggestFaqAnswersResponse', + ) + suggest_smart_replies_response = proto.Field( + proto.MESSAGE, + number=4, + oneof='suggestion_response', + message='SuggestSmartRepliesResponse', + ) + + +class SuggestArticlesRequest(proto.Message): + r"""The request message for + [Participants.SuggestArticles][google.cloud.dialogflow.v2beta1.Participants.SuggestArticles]. + + Attributes: + parent (str): + Required. The name of the participant to fetch suggestion + for. Format: + ``projects//locations//conversations//participants/``. + latest_message (str): + Optional. The name of the latest conversation message to + compile suggestion for. If empty, it will be the latest + message of the conversation. + + Format: + ``projects//locations//conversations//messages/``. + context_size (int): + Optional. Max number of messages prior to and including + [latest_message][google.cloud.dialogflow.v2beta1.SuggestArticlesRequest.latest_message] + to use as context when compiling the suggestion. By default + 20 and at most 50. + assist_query_params (google.cloud.dialogflow_v2beta1.types.AssistQueryParameters): + Optional. Parameters for a human assist + query. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + latest_message = proto.Field( + proto.STRING, + number=2, + ) + context_size = proto.Field( + proto.INT32, + number=3, + ) + assist_query_params = proto.Field( + proto.MESSAGE, + number=4, + message='AssistQueryParameters', + ) + + +class SuggestArticlesResponse(proto.Message): + r"""The response message for + [Participants.SuggestArticles][google.cloud.dialogflow.v2beta1.Participants.SuggestArticles]. + + Attributes: + article_answers (Sequence[google.cloud.dialogflow_v2beta1.types.ArticleAnswer]): + Output only. Articles ordered by score in + descending order. + latest_message (str): + The name of the latest conversation message used to compile + suggestion for. + + Format: + ``projects//locations//conversations//messages/``. + context_size (int): + Number of messages prior to and including + [latest_message][google.cloud.dialogflow.v2beta1.SuggestArticlesResponse.latest_message] + to compile the suggestion. It may be smaller than the + [SuggestArticlesResponse.context_size][google.cloud.dialogflow.v2beta1.SuggestArticlesResponse.context_size] + field in the request if there aren't that many messages in + the conversation. + """ + + article_answers = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ArticleAnswer', + ) + latest_message = proto.Field( + proto.STRING, + number=2, + ) + context_size = proto.Field( + proto.INT32, + number=3, + ) + + +class SuggestFaqAnswersRequest(proto.Message): + r"""The request message for + [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers]. + + Attributes: + parent (str): + Required. The name of the participant to fetch suggestion + for. Format: + ``projects//locations//conversations//participants/``. + latest_message (str): + Optional. The name of the latest conversation message to + compile suggestion for. If empty, it will be the latest + message of the conversation. + + Format: + ``projects//locations//conversations//messages/``. + context_size (int): + Optional. Max number of messages prior to and including + [latest_message] to use as context when compiling the + suggestion. By default 20 and at most 50. + assist_query_params (google.cloud.dialogflow_v2beta1.types.AssistQueryParameters): + Optional. Parameters for a human assist + query. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + latest_message = proto.Field( + proto.STRING, + number=2, + ) + context_size = proto.Field( + proto.INT32, + number=3, + ) + assist_query_params = proto.Field( + proto.MESSAGE, + number=4, + message='AssistQueryParameters', + ) + + +class SuggestFaqAnswersResponse(proto.Message): + r"""The request message for + [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers]. + + Attributes: + faq_answers (Sequence[google.cloud.dialogflow_v2beta1.types.FaqAnswer]): + Output only. Answers extracted from FAQ + documents. + latest_message (str): + The name of the latest conversation message used to compile + suggestion for. + + Format: + ``projects//locations//conversations//messages/``. + context_size (int): + Number of messages prior to and including + [latest_message][google.cloud.dialogflow.v2beta1.SuggestFaqAnswersResponse.latest_message] + to compile the suggestion. It may be smaller than the + [SuggestFaqAnswersRequest.context_size][google.cloud.dialogflow.v2beta1.SuggestFaqAnswersRequest.context_size] + field in the request if there aren't that many messages in + the conversation. + """ + + faq_answers = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='FaqAnswer', + ) + latest_message = proto.Field( + proto.STRING, + number=2, + ) + context_size = proto.Field( + proto.INT32, + number=3, + ) + + +class SuggestSmartRepliesRequest(proto.Message): + r"""The request message for + [Participants.SuggestSmartReplies][google.cloud.dialogflow.v2beta1.Participants.SuggestSmartReplies]. + + Attributes: + parent (str): + Required. The name of the participant to fetch suggestion + for. Format: + ``projects//locations//conversations//participants/``. + current_text_input (google.cloud.dialogflow_v2beta1.types.TextInput): + The current natural language text segment to + compile suggestion for. This provides a way for + user to get follow up smart reply suggestion + after a smart reply selection, without sending a + text message. + latest_message (str): + The name of the latest conversation message to compile + suggestion for. If empty, it will be the latest message of + the conversation. + + Format: + ``projects//locations//conversations//messages/``. + context_size (int): + Optional. Max number of messages prior to and including + [latest_message] to use as context when compiling the + suggestion. By default 20 and at most 50. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + current_text_input = proto.Field( + proto.MESSAGE, + number=4, + message=session.TextInput, + ) + latest_message = proto.Field( + proto.STRING, + number=2, + ) + context_size = proto.Field( + proto.INT32, + number=3, + ) + + +class SuggestSmartRepliesResponse(proto.Message): + r"""The response message for + [Participants.SuggestSmartReplies][google.cloud.dialogflow.v2beta1.Participants.SuggestSmartReplies]. + + Attributes: + smart_reply_answers (Sequence[google.cloud.dialogflow_v2beta1.types.SmartReplyAnswer]): + Output only. Multiple reply options provided + by smart reply service. The order is based on + the rank of the model prediction. The maximum + number of the returned replies is set in + SmartReplyConfig. + latest_message (str): + The name of the latest conversation message used to compile + suggestion for. + + Format: + ``projects//locations//conversations//messages/``. + context_size (int): + Number of messages prior to and including + [latest_message][google.cloud.dialogflow.v2beta1.SuggestSmartRepliesResponse.latest_message] + to compile the suggestion. It may be smaller than the + [SuggestSmartRepliesRequest.context_size][google.cloud.dialogflow.v2beta1.SuggestSmartRepliesRequest.context_size] + field in the request if there aren't that many messages in + the conversation. + """ + + smart_reply_answers = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SmartReplyAnswer', + ) + latest_message = proto.Field( + proto.STRING, + number=2, + ) + context_size = proto.Field( + proto.INT32, + number=3, + ) + + +class Suggestion(proto.Message): + r"""Represents a suggestion for a human agent. + + Attributes: + name (str): + Output only. The name of this suggestion. Format: + ``projects//locations//conversations//participants/*/suggestions/``. + articles (Sequence[google.cloud.dialogflow_v2beta1.types.Suggestion.Article]): + Output only. Articles ordered by score in + descending order. + faq_answers (Sequence[google.cloud.dialogflow_v2beta1.types.Suggestion.FaqAnswer]): + Output only. Answers extracted from FAQ + documents. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the suggestion was + created. + latest_message (str): + Output only. Latest message used as context to compile this + suggestion. + + Format: + ``projects//locations//conversations//messages/``. + """ + + class Article(proto.Message): + r"""Represents suggested article. + + Attributes: + title (str): + Output only. The article title. + uri (str): + Output only. The article URI. + snippets (Sequence[str]): + Output only. Article snippets. + metadata (Sequence[google.cloud.dialogflow_v2beta1.types.Suggestion.Article.MetadataEntry]): + Output only. A map that contains metadata + about the answer and the document from which it + originates. + answer_record (str): + Output only. The name of answer record, in + the format of "projects//locations//answerRecords/". + """ + + title = proto.Field( + proto.STRING, + number=1, + ) + uri = proto.Field( + proto.STRING, + number=2, + ) + snippets = proto.RepeatedField( + proto.STRING, + number=3, + ) + metadata = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + answer_record = proto.Field( + proto.STRING, + number=6, + ) + + class FaqAnswer(proto.Message): + r"""Represents suggested answer from "frequently asked + questions". + + Attributes: + answer (str): + Output only. The piece of text from the ``source`` knowledge + base document. + confidence (float): + The system's confidence score that this + Knowledge answer is a good match for this + conversational query, range from 0.0 (completely + uncertain) to 1.0 (completely certain). + question (str): + Output only. The corresponding FAQ question. + source (str): + Output only. Indicates which Knowledge Document this answer + was extracted from. Format: + ``projects//locations//agent/knowledgeBases//documents/``. + metadata (Sequence[google.cloud.dialogflow_v2beta1.types.Suggestion.FaqAnswer.MetadataEntry]): + Output only. A map that contains metadata + about the answer and the document from which it + originates. + answer_record (str): + Output only. The name of answer record, in + the format of "projects//locations//answerRecords/". + """ + + answer = proto.Field( + proto.STRING, + number=1, + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + question = proto.Field( + proto.STRING, + number=3, + ) + source = proto.Field( + proto.STRING, + number=4, + ) + metadata = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + answer_record = proto.Field( + proto.STRING, + number=6, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + articles = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Article, + ) + faq_answers = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=FaqAnswer, + ) + create_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + latest_message = proto.Field( + proto.STRING, + number=7, + ) + + +class ListSuggestionsRequest(proto.Message): + r"""The request message for + [Participants.ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions]. + + Attributes: + parent (str): + Required. The name of the participant to fetch suggestions + for. Format: + ``projects//locations//conversations//participants/``. + page_size (int): + Optional. The maximum number of items to + return in a single page. The default value is + 100; the maximum value is 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + filter (str): + Optional. Filter on suggestions fields. Currently predicates + on ``create_time`` and ``create_time_epoch_microseconds`` + are supported. ``create_time`` only support milliseconds + accuracy. E.g., + ``create_time_epoch_microseconds > 1551790877964485`` or + ``create_time > "2017-01-15T01:30:15.01Z"`` + + For more information about filtering, see `API + Filtering `__. + """ + + 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 ListSuggestionsResponse(proto.Message): + r"""The response message for + [Participants.ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions]. + + Attributes: + suggestions (Sequence[google.cloud.dialogflow_v2beta1.types.Suggestion]): + Required. The list of suggestions. There will be a maximum + number of items returned based on the page_size field in the + request. ``suggestions`` is sorted by ``create_time`` in + descending order. + next_page_token (str): + Optional. Token to retrieve the next page of + results or empty if there are no more results in + the list. + """ + + @property + def raw_page(self): + return self + + suggestions = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Suggestion', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class CompileSuggestionRequest(proto.Message): + r"""The request message for + [Participants.CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion]. + + Attributes: + parent (str): + Required. The name of the participant to fetch suggestion + for. Format: + ``projects//locations//conversations//participants/``. + latest_message (str): + Optional. The name of the latest conversation message to + compile suggestion for. If empty, it will be the latest + message of the conversation. + + Format: + ``projects//locations//conversations//messages/``. + context_size (int): + Optional. Max number of messages prior to and including + [latest_message] to use as context when compiling the + suggestion. If zero or less than zero, 20 is used. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + latest_message = proto.Field( + proto.STRING, + number=2, + ) + context_size = proto.Field( + proto.INT32, + number=3, + ) + + +class CompileSuggestionResponse(proto.Message): + r"""The response message for + [Participants.CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion]. + + Attributes: + suggestion (google.cloud.dialogflow_v2beta1.types.Suggestion): + The compiled suggestion. + latest_message (str): + The name of the latest conversation message used to compile + suggestion for. + + Format: + ``projects//locations//conversations//messages/``. + context_size (int): + Number of messages prior to and including + [latest_message][google.cloud.dialogflow.v2beta1.CompileSuggestionResponse.latest_message] + to compile the suggestion. It may be smaller than the + [CompileSuggestionRequest.context_size][google.cloud.dialogflow.v2beta1.CompileSuggestionRequest.context_size] + field in the request if there aren't that many messages in + the conversation. + """ + + suggestion = proto.Field( + proto.MESSAGE, + number=1, + message='Suggestion', + ) + latest_message = proto.Field( + proto.STRING, + number=2, + ) + context_size = proto.Field( + proto.INT32, + number=3, + ) + + +class ResponseMessage(proto.Message): + r"""Response messages from an automated agent. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + text (google.cloud.dialogflow_v2beta1.types.ResponseMessage.Text): + Returns a text response. + + This field is a member of `oneof`_ ``message``. + payload (google.protobuf.struct_pb2.Struct): + Returns a response containing a custom, + platform-specific payload. + + This field is a member of `oneof`_ ``message``. + live_agent_handoff (google.cloud.dialogflow_v2beta1.types.ResponseMessage.LiveAgentHandoff): + Hands off conversation to a live agent. + + This field is a member of `oneof`_ ``message``. + end_interaction (google.cloud.dialogflow_v2beta1.types.ResponseMessage.EndInteraction): + A signal that indicates the interaction with + the Dialogflow agent has ended. + + This field is a member of `oneof`_ ``message``. + telephony_transfer_call (google.cloud.dialogflow_v2beta1.types.ResponseMessage.TelephonyTransferCall): + A signal that the client should transfer the + phone call connected to this agent to a third- + party endpoint. + + This field is a member of `oneof`_ ``message``. + """ + + class Text(proto.Message): + r"""The text response message. + + Attributes: + text (Sequence[str]): + A collection of text responses. + """ + + text = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class LiveAgentHandoff(proto.Message): + r"""Indicates that the conversation should be handed off to a human + agent. + + Dialogflow only uses this to determine which conversations were + handed off to a human agent for measurement purposes. What else to + do with this signal is up to you and your handoff procedures. + + You may set this, for example: + + - In the entry fulfillment of a CX Page if entering the page + indicates something went extremely wrong in the conversation. + - In a webhook response when you determine that the customer issue + can only be handled by a human. + + Attributes: + metadata (google.protobuf.struct_pb2.Struct): + Custom metadata for your handoff procedure. + Dialogflow doesn't impose any structure on this. + """ + + metadata = proto.Field( + proto.MESSAGE, + number=1, + message=struct_pb2.Struct, + ) + + class EndInteraction(proto.Message): + r"""Indicates that interaction with the Dialogflow agent has + ended. + + """ + + class TelephonyTransferCall(proto.Message): + r"""Represents the signal that telles the client to transfer the + phone call connected to the agent to a third-party endpoint. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + phone_number (str): + Transfer the call to a phone number in `E.164 + format `__. + + This field is a member of `oneof`_ ``endpoint``. + sip_uri (str): + Transfer the call to a SIP endpoint. + + This field is a member of `oneof`_ ``endpoint``. + """ + + phone_number = proto.Field( + proto.STRING, + number=1, + oneof='endpoint', + ) + sip_uri = proto.Field( + proto.STRING, + number=2, + oneof='endpoint', + ) + + text = proto.Field( + proto.MESSAGE, + number=1, + oneof='message', + message=Text, + ) + payload = proto.Field( + proto.MESSAGE, + number=2, + oneof='message', + message=struct_pb2.Struct, + ) + live_agent_handoff = proto.Field( + proto.MESSAGE, + number=3, + oneof='message', + message=LiveAgentHandoff, + ) + end_interaction = proto.Field( + proto.MESSAGE, + number=4, + oneof='message', + message=EndInteraction, + ) + telephony_transfer_call = proto.Field( + proto.MESSAGE, + number=6, + oneof='message', + message=TelephonyTransferCall, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/session.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/session.py new file mode 100644 index 000000000..d39ba0dde --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/session.py @@ -0,0 +1,1197 @@ +# -*- 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.dialogflow_v2beta1.types import agent +from google.cloud.dialogflow_v2beta1.types import audio_config as gcd_audio_config +from google.cloud.dialogflow_v2beta1.types import context +from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent +from google.cloud.dialogflow_v2beta1.types import session_entity_type +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2beta1', + manifest={ + 'DetectIntentRequest', + 'DetectIntentResponse', + 'QueryParameters', + 'QueryInput', + 'QueryResult', + 'KnowledgeAnswers', + 'StreamingDetectIntentRequest', + 'StreamingDetectIntentResponse', + 'StreamingRecognitionResult', + 'TextInput', + 'EventInput', + 'SentimentAnalysisRequestConfig', + 'SentimentAnalysisResult', + 'Sentiment', + }, +) + + +class DetectIntentRequest(proto.Message): + r"""The request to detect user's intent. + + Attributes: + session (str): + Required. The name of the session this query is sent to. + Supported formats: + + - \`projects//agent/sessions/, + - ``projects//locations//agent/sessions/``, + - ``projects//agent/environments//users//sessions/``, + - ``projects//locations//agent/environments//users//sessions/``, + + If ``Location ID`` is not specified we assume default 'us' + location. If ``Environment ID`` is not specified, we assume + default 'draft' environment (``Environment ID`` might be + referred to as environment name at some places). If + ``User ID`` is not specified, we are using "-". It's up to + the API caller to choose an appropriate ``Session ID`` and + ``User Id``. They can be a random number or some type of + user and session identifiers (preferably hashed). The length + of the ``Session ID`` and ``User ID`` must not exceed 36 + characters. For more information, see the `API interactions + guide `__. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + query_params (google.cloud.dialogflow_v2beta1.types.QueryParameters): + The parameters of this query. + query_input (google.cloud.dialogflow_v2beta1.types.QueryInput): + Required. The input specification. It can be + set to: + 1. an audio config + which instructs the speech recognizer how to + process the speech audio, + 2. a conversational query in the form of text, + or + 3. an event that specifies which intent to + trigger. + output_audio_config (google.cloud.dialogflow_v2beta1.types.OutputAudioConfig): + Instructs the speech synthesizer how to + generate the output audio. If this field is not + set and agent-level speech synthesizer is not + configured, no output audio is generated. + output_audio_config_mask (google.protobuf.field_mask_pb2.FieldMask): + Mask for + [output_audio_config][google.cloud.dialogflow.v2beta1.DetectIntentRequest.output_audio_config] + indicating which settings in this request-level config + should override speech synthesizer settings defined at + agent-level. + + If unspecified or empty, + [output_audio_config][google.cloud.dialogflow.v2beta1.DetectIntentRequest.output_audio_config] + replaces the agent-level config in its entirety. + input_audio (bytes): + The natural language speech audio to be processed. This + field should be populated iff ``query_input`` is set to an + input audio config. A single request can contain up to 1 + minute of speech audio data. + """ + + session = proto.Field( + proto.STRING, + number=1, + ) + query_params = proto.Field( + proto.MESSAGE, + number=2, + message='QueryParameters', + ) + query_input = proto.Field( + proto.MESSAGE, + number=3, + message='QueryInput', + ) + output_audio_config = proto.Field( + proto.MESSAGE, + number=4, + message=gcd_audio_config.OutputAudioConfig, + ) + output_audio_config_mask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + input_audio = proto.Field( + proto.BYTES, + number=5, + ) + + +class DetectIntentResponse(proto.Message): + r"""The message returned from the DetectIntent method. + + Attributes: + response_id (str): + The unique identifier of the response. It can + be used to locate a response in the training + example set or for reporting issues. + query_result (google.cloud.dialogflow_v2beta1.types.QueryResult): + The selected results of the conversational query or event + processing. See ``alternative_query_results`` for additional + potential results. + alternative_query_results (Sequence[google.cloud.dialogflow_v2beta1.types.QueryResult]): + If Knowledge Connectors are enabled, there could be more + than one result returned for a given query or event, and + this field will contain all results except for the top one, + which is captured in query_result. The alternative results + are ordered by decreasing + ``QueryResult.intent_detection_confidence``. If Knowledge + Connectors are disabled, this field will be empty until + multiple responses for regular intents are supported, at + which point those additional results will be surfaced here. + webhook_status (google.rpc.status_pb2.Status): + Specifies the status of the webhook request. + output_audio (bytes): + The audio data bytes encoded as specified in the request. + Note: The output audio is generated based on the values of + default platform text responses found in the + ``query_result.fulfillment_messages`` field. If multiple + default text responses exist, they will be concatenated when + generating audio. If no default platform text responses + exist, the generated audio content will be empty. + + In some scenarios, multiple output audio fields may be + present in the response structure. In these cases, only the + top-most-level audio output has content. + output_audio_config (google.cloud.dialogflow_v2beta1.types.OutputAudioConfig): + The config used by the speech synthesizer to + generate the output audio. + """ + + response_id = proto.Field( + proto.STRING, + number=1, + ) + query_result = proto.Field( + proto.MESSAGE, + number=2, + message='QueryResult', + ) + alternative_query_results = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='QueryResult', + ) + webhook_status = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + output_audio = proto.Field( + proto.BYTES, + number=4, + ) + output_audio_config = proto.Field( + proto.MESSAGE, + number=6, + message=gcd_audio_config.OutputAudioConfig, + ) + + +class QueryParameters(proto.Message): + r"""Represents the parameters of the conversational query. + + Attributes: + time_zone (str): + The time zone of this conversational query from the `time + zone database `__, e.g., + America/New_York, Europe/Paris. If not provided, the time + zone specified in agent settings is used. + geo_location (google.type.latlng_pb2.LatLng): + The geo location of this conversational + query. + contexts (Sequence[google.cloud.dialogflow_v2beta1.types.Context]): + The collection of contexts to be activated + before this query is executed. + reset_contexts (bool): + Specifies whether to delete all contexts in + the current session before the new ones are + activated. + session_entity_types (Sequence[google.cloud.dialogflow_v2beta1.types.SessionEntityType]): + Additional session entity types to replace or + extend developer entity types with. The entity + synonyms apply to all languages and persist for + the session of this query. + payload (google.protobuf.struct_pb2.Struct): + This field can be used to pass custom data to your webhook. + Arbitrary JSON objects are supported. If supplied, the value + is used to populate the + ``WebhookRequest.original_detect_intent_request.payload`` + field sent to your webhook. + knowledge_base_names (Sequence[str]): + KnowledgeBases to get alternative results from. If not set, + the KnowledgeBases enabled in the agent (through UI) will be + used. Format: + ``projects//knowledgeBases/``. + sentiment_analysis_request_config (google.cloud.dialogflow_v2beta1.types.SentimentAnalysisRequestConfig): + Configures the type of sentiment analysis to + perform. If not provided, sentiment analysis is + not performed. Note: Sentiment Analysis is only + currently available for Essentials Edition + agents. + sub_agents (Sequence[google.cloud.dialogflow_v2beta1.types.SubAgent]): + For mega agent query, directly specify which + sub agents to query. If any specified sub agent + is not linked to the mega agent, an error will + be returned. If empty, Dialogflow will decide + which sub agents to query. If specified for a + non-mega-agent query, will be silently ignored. + webhook_headers (Sequence[google.cloud.dialogflow_v2beta1.types.QueryParameters.WebhookHeadersEntry]): + This field can be used to pass HTTP headers + for a webhook call. These headers will be sent + to webhook along with the headers that have been + configured through Dialogflow web console. The + headers defined within this field will overwrite + the headers configured through Dialogflow + console if there is a conflict. Header names are + case-insensitive. Google's specified headers are + not allowed. Including: "Host", "Content- + Length", "Connection", "From", "User-Agent", + "Accept-Encoding", "If-Modified-Since", "If- + None-Match", "X-Forwarded-For", etc. + """ + + time_zone = proto.Field( + proto.STRING, + number=1, + ) + geo_location = proto.Field( + proto.MESSAGE, + number=2, + message=latlng_pb2.LatLng, + ) + contexts = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=context.Context, + ) + reset_contexts = proto.Field( + proto.BOOL, + number=4, + ) + session_entity_types = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=session_entity_type.SessionEntityType, + ) + payload = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + knowledge_base_names = proto.RepeatedField( + proto.STRING, + number=12, + ) + sentiment_analysis_request_config = proto.Field( + proto.MESSAGE, + number=10, + message='SentimentAnalysisRequestConfig', + ) + sub_agents = proto.RepeatedField( + proto.MESSAGE, + number=13, + message=agent.SubAgent, + ) + webhook_headers = proto.MapField( + proto.STRING, + proto.STRING, + number=14, + ) + + +class QueryInput(proto.Message): + r"""Represents the query input. It can contain either: + 1. An audio config which + instructs the speech recognizer how to process the speech + audio. + 2. A conversational query in the form of text. + + 3. An event that specifies which intent to trigger. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + audio_config (google.cloud.dialogflow_v2beta1.types.InputAudioConfig): + Instructs the speech recognizer how to + process the speech audio. + + This field is a member of `oneof`_ ``input``. + text (google.cloud.dialogflow_v2beta1.types.TextInput): + The natural language text to be processed. + + This field is a member of `oneof`_ ``input``. + event (google.cloud.dialogflow_v2beta1.types.EventInput): + The event to be processed. + + This field is a member of `oneof`_ ``input``. + dtmf (google.cloud.dialogflow_v2beta1.types.TelephonyDtmfEvents): + The DTMF digits used to invoke intent and + fill in parameter value. + + This field is a member of `oneof`_ ``input``. + """ + + audio_config = proto.Field( + proto.MESSAGE, + number=1, + oneof='input', + message=gcd_audio_config.InputAudioConfig, + ) + text = proto.Field( + proto.MESSAGE, + number=2, + oneof='input', + message='TextInput', + ) + event = proto.Field( + proto.MESSAGE, + number=3, + oneof='input', + message='EventInput', + ) + dtmf = proto.Field( + proto.MESSAGE, + number=4, + oneof='input', + message=gcd_audio_config.TelephonyDtmfEvents, + ) + + +class QueryResult(proto.Message): + r"""Represents the result of conversational query or event + processing. + + Attributes: + query_text (str): + The original conversational query text: + + - If natural language text was provided as input, + ``query_text`` contains a copy of the input. + - If natural language speech audio was provided as input, + ``query_text`` contains the speech recognition result. If + speech recognizer produced multiple alternatives, a + particular one is picked. + - If automatic spell correction is enabled, ``query_text`` + will contain the corrected user input. + language_code (str): + The language that was triggered during intent detection. See + `Language + Support `__ + for a list of the currently supported language codes. + speech_recognition_confidence (float): + The Speech recognition confidence between 0.0 + and 1.0. A higher number indicates an estimated + greater likelihood that the recognized words are + correct. The default of 0.0 is a sentinel value + indicating that confidence was not set. + + This field is not guaranteed to be accurate or + set. In particular this field isn't set for + StreamingDetectIntent since the streaming + endpoint has separate confidence estimates per + portion of the audio in + StreamingRecognitionResult. + action (str): + The action name from the matched intent. + parameters (google.protobuf.struct_pb2.Struct): + The collection of extracted parameters. + Depending on your protocol or client library + language, this is a map, associative array, + symbol table, dictionary, or JSON object + composed of a collection of (MapKey, MapValue) + pairs: + - MapKey type: string + - MapKey value: parameter name + - MapValue type: + - If parameter's entity type is a + composite entity: map - Else: depending on + parameter value type, could be one of string, + number, boolean, null, list or map + - MapValue value: + - If parameter's entity type is a + composite entity: map from composite + entity property names to property values - + Else: parameter value + all_required_params_present (bool): + This field is set to: + + - ``false`` if the matched intent has required parameters + and not all of the required parameter values have been + collected. + - ``true`` if all required parameter values have been + collected, or if the matched intent doesn't contain any + required parameters. + cancels_slot_filling (bool): + Indicates whether the conversational query + triggers a cancellation for slot filling. + fulfillment_text (str): + The text to be pronounced to the user or shown on the + screen. Note: This is a legacy field, + ``fulfillment_messages`` should be preferred. + fulfillment_messages (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message]): + The collection of rich messages to present to + the user. + webhook_source (str): + If the query was fulfilled by a webhook call, this field is + set to the value of the ``source`` field returned in the + webhook response. + webhook_payload (google.protobuf.struct_pb2.Struct): + If the query was fulfilled by a webhook call, this field is + set to the value of the ``payload`` field returned in the + webhook response. + output_contexts (Sequence[google.cloud.dialogflow_v2beta1.types.Context]): + The collection of output contexts. If applicable, + ``output_contexts.parameters`` contains entries with name + ``.original`` containing the original + parameter values before the query. + intent (google.cloud.dialogflow_v2beta1.types.Intent): + The intent that matched the conversational query. Some, not + all fields are filled in this message, including but not + limited to: ``name``, ``display_name``, ``end_interaction`` + and ``is_fallback``. + intent_detection_confidence (float): + The intent detection confidence. Values range from 0.0 + (completely uncertain) to 1.0 (completely certain). This + value is for informational purpose only and is only used to + help match the best intent within the classification + threshold. This value may change for the same end-user + expression at any time due to a model retraining or change + in implementation. If there are + ``multiple knowledge_answers`` messages, this value is set + to the greatest ``knowledgeAnswers.match_confidence`` value + in the list. + diagnostic_info (google.protobuf.struct_pb2.Struct): + Free-form diagnostic information for the + associated detect intent request. The fields of + this data can change without notice, so you + should not write code that depends on its + structure. + The data may contain: + + - webhook call latency + - webhook errors + sentiment_analysis_result (google.cloud.dialogflow_v2beta1.types.SentimentAnalysisResult): + The sentiment analysis result, which depends on the + ``sentiment_analysis_request_config`` specified in the + request. + knowledge_answers (google.cloud.dialogflow_v2beta1.types.KnowledgeAnswers): + The result from Knowledge Connector (if any), ordered by + decreasing ``KnowledgeAnswers.match_confidence``. + """ + + query_text = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=15, + ) + speech_recognition_confidence = proto.Field( + proto.FLOAT, + number=2, + ) + action = proto.Field( + proto.STRING, + number=3, + ) + parameters = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Struct, + ) + all_required_params_present = proto.Field( + proto.BOOL, + number=5, + ) + cancels_slot_filling = proto.Field( + proto.BOOL, + number=21, + ) + fulfillment_text = proto.Field( + proto.STRING, + number=6, + ) + fulfillment_messages = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=gcd_intent.Intent.Message, + ) + webhook_source = proto.Field( + proto.STRING, + number=8, + ) + webhook_payload = proto.Field( + proto.MESSAGE, + number=9, + message=struct_pb2.Struct, + ) + output_contexts = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=context.Context, + ) + intent = proto.Field( + proto.MESSAGE, + number=11, + message=gcd_intent.Intent, + ) + intent_detection_confidence = proto.Field( + proto.FLOAT, + number=12, + ) + diagnostic_info = proto.Field( + proto.MESSAGE, + number=14, + message=struct_pb2.Struct, + ) + sentiment_analysis_result = proto.Field( + proto.MESSAGE, + number=17, + message='SentimentAnalysisResult', + ) + knowledge_answers = proto.Field( + proto.MESSAGE, + number=18, + message='KnowledgeAnswers', + ) + + +class KnowledgeAnswers(proto.Message): + r"""Represents the result of querying a Knowledge base. + + Attributes: + answers (Sequence[google.cloud.dialogflow_v2beta1.types.KnowledgeAnswers.Answer]): + A list of answers from Knowledge Connector. + """ + + class Answer(proto.Message): + r"""An answer from Knowledge Connector. + + Attributes: + source (str): + Indicates which Knowledge Document this answer was extracted + from. Format: + ``projects//knowledgeBases//documents/``. + faq_question (str): + The corresponding FAQ question if the answer + was extracted from a FAQ Document, empty + otherwise. + answer (str): + The piece of text from the ``source`` knowledge base + document that answers this conversational query. + match_confidence_level (google.cloud.dialogflow_v2beta1.types.KnowledgeAnswers.Answer.MatchConfidenceLevel): + The system's confidence level that this knowledge answer is + a good match for this conversational query. NOTE: The + confidence level for a given ```` pair may + change without notice, as it depends on models that are + constantly being improved. However, it will change less + frequently than the confidence score below, and should be + preferred for referencing the quality of an answer. + match_confidence (float): + The system's confidence score that this Knowledge answer is + a good match for this conversational query. The range is + from 0.0 (completely uncertain) to 1.0 (completely certain). + Note: The confidence score is likely to vary somewhat + (possibly even for identical requests), as the underlying + model is under constant improvement. It may be deprecated in + the future. We recommend using ``match_confidence_level`` + which should be generally more stable. + """ + class MatchConfidenceLevel(proto.Enum): + r"""Represents the system's confidence that this knowledge answer + is a good match for this conversational query. + """ + MATCH_CONFIDENCE_LEVEL_UNSPECIFIED = 0 + LOW = 1 + MEDIUM = 2 + HIGH = 3 + + source = proto.Field( + proto.STRING, + number=1, + ) + faq_question = proto.Field( + proto.STRING, + number=2, + ) + answer = proto.Field( + proto.STRING, + number=3, + ) + match_confidence_level = proto.Field( + proto.ENUM, + number=4, + enum='KnowledgeAnswers.Answer.MatchConfidenceLevel', + ) + match_confidence = proto.Field( + proto.FLOAT, + number=5, + ) + + answers = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Answer, + ) + + +class StreamingDetectIntentRequest(proto.Message): + r"""The top-level message sent by the client to the + [Sessions.StreamingDetectIntent][google.cloud.dialogflow.v2beta1.Sessions.StreamingDetectIntent] + method. + + Multiple request messages should be sent in order: + + 1. The first message must contain + [session][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.session], + [query_input][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_input] + plus optionally + [query_params][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_params]. + If the client wants to receive an audio response, it should also + contain + [output_audio_config][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.output_audio_config]. + The message must not contain + [input_audio][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.input_audio]. + + 2. If + [query_input][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_input] + was set to + [query_input.audio_config][google.cloud.dialogflow.v2beta1.InputAudioConfig], + all subsequent messages must contain + [input_audio][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.input_audio] + to continue with Speech recognition. If you decide to rather + detect an intent from text input after you already started Speech + recognition, please send a message with + [query_input.text][google.cloud.dialogflow.v2beta1.QueryInput.text]. + + However, note that: + + - Dialogflow will bill you for the audio duration so far. + - Dialogflow discards all Speech recognition results in favor of + the input text. + - Dialogflow will use the language code from the first message. + + After you sent all input, you must half-close or abort the request + stream. + + Attributes: + session (str): + Required. The name of the session the query is sent to. + Supported formats: + + - \`projects//agent/sessions/, + - ``projects//locations//agent/sessions/``, + - ``projects//agent/environments//users//sessions/``, + - ``projects//locations//agent/environments//users//sessions/``, + + If ``Location ID`` is not specified we assume default 'us' + location. If ``Environment ID`` is not specified, we assume + default 'draft' environment. If ``User ID`` is not + specified, we are using "-". It's up to the API caller to + choose an appropriate ``Session ID`` and ``User Id``. They + can be a random number or some type of user and session + identifiers (preferably hashed). The length of the + ``Session ID`` and ``User ID`` must not exceed 36 + characters. + + For more information, see the `API interactions + guide `__. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + query_params (google.cloud.dialogflow_v2beta1.types.QueryParameters): + The parameters of this query. + query_input (google.cloud.dialogflow_v2beta1.types.QueryInput): + Required. The input specification. It can be + set to: + 1. an audio config which instructs the speech + recognizer how to process the speech audio, + + 2. a conversational query in the form of text, + or + 3. an event that specifies which intent to + trigger. + single_utterance (bool): + DEPRECATED. Please use + [InputAudioConfig.single_utterance][google.cloud.dialogflow.v2beta1.InputAudioConfig.single_utterance] + instead. If ``false`` (default), recognition does not cease + until the client closes the stream. If ``true``, the + recognizer will detect a single spoken utterance in input + audio. Recognition ceases when it detects the audio's voice + has stopped or paused. In this case, once a detected intent + is received, the client should close the stream and start a + new request with a new stream as needed. This setting is + ignored when ``query_input`` is a piece of text or an event. + output_audio_config (google.cloud.dialogflow_v2beta1.types.OutputAudioConfig): + Instructs the speech synthesizer how to + generate the output audio. If this field is not + set and agent-level speech synthesizer is not + configured, no output audio is generated. + output_audio_config_mask (google.protobuf.field_mask_pb2.FieldMask): + Mask for + [output_audio_config][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.output_audio_config] + indicating which settings in this request-level config + should override speech synthesizer settings defined at + agent-level. + + If unspecified or empty, + [output_audio_config][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.output_audio_config] + replaces the agent-level config in its entirety. + input_audio (bytes): + The input audio content to be recognized. Must be sent if + ``query_input`` was set to a streaming input audio config. + The complete audio over all streaming messages must not + exceed 1 minute. + """ + + session = proto.Field( + proto.STRING, + number=1, + ) + query_params = proto.Field( + proto.MESSAGE, + number=2, + message='QueryParameters', + ) + query_input = proto.Field( + proto.MESSAGE, + number=3, + message='QueryInput', + ) + single_utterance = proto.Field( + proto.BOOL, + number=4, + ) + output_audio_config = proto.Field( + proto.MESSAGE, + number=5, + message=gcd_audio_config.OutputAudioConfig, + ) + output_audio_config_mask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + input_audio = proto.Field( + proto.BYTES, + number=6, + ) + + +class StreamingDetectIntentResponse(proto.Message): + r"""The top-level message returned from the ``StreamingDetectIntent`` + method. + + Multiple response messages can be returned in order: + + 1. If the ``StreamingDetectIntentRequest.input_audio`` field was + set, the ``recognition_result`` field is populated for one or + more messages. See the + [StreamingRecognitionResult][google.cloud.dialogflow.v2beta1.StreamingRecognitionResult] + message for details about the result message sequence. + + 2. The next message contains ``response_id``, ``query_result``, + ``alternative_query_results`` and optionally ``webhook_status`` + if a WebHook was called. + + 3. If ``output_audio_config`` was specified in the request or + agent-level speech synthesizer is configured, all subsequent + messages contain ``output_audio`` and ``output_audio_config``. + + Attributes: + response_id (str): + The unique identifier of the response. It can + be used to locate a response in the training + example set or for reporting issues. + recognition_result (google.cloud.dialogflow_v2beta1.types.StreamingRecognitionResult): + The result of speech recognition. + query_result (google.cloud.dialogflow_v2beta1.types.QueryResult): + The selected results of the conversational query or event + processing. See ``alternative_query_results`` for additional + potential results. + alternative_query_results (Sequence[google.cloud.dialogflow_v2beta1.types.QueryResult]): + If Knowledge Connectors are enabled, there could be more + than one result returned for a given query or event, and + this field will contain all results except for the top one, + which is captured in query_result. The alternative results + are ordered by decreasing + ``QueryResult.intent_detection_confidence``. If Knowledge + Connectors are disabled, this field will be empty until + multiple responses for regular intents are supported, at + which point those additional results will be surfaced here. + webhook_status (google.rpc.status_pb2.Status): + Specifies the status of the webhook request. + output_audio (bytes): + The audio data bytes encoded as specified in the request. + Note: The output audio is generated based on the values of + default platform text responses found in the + ``query_result.fulfillment_messages`` field. If multiple + default text responses exist, they will be concatenated when + generating audio. If no default platform text responses + exist, the generated audio content will be empty. + + In some scenarios, multiple output audio fields may be + present in the response structure. In these cases, only the + top-most-level audio output has content. + output_audio_config (google.cloud.dialogflow_v2beta1.types.OutputAudioConfig): + The config used by the speech synthesizer to + generate the output audio. + """ + + response_id = proto.Field( + proto.STRING, + number=1, + ) + recognition_result = proto.Field( + proto.MESSAGE, + number=2, + message='StreamingRecognitionResult', + ) + query_result = proto.Field( + proto.MESSAGE, + number=3, + message='QueryResult', + ) + alternative_query_results = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='QueryResult', + ) + webhook_status = proto.Field( + proto.MESSAGE, + number=4, + message=status_pb2.Status, + ) + output_audio = proto.Field( + proto.BYTES, + number=5, + ) + output_audio_config = proto.Field( + proto.MESSAGE, + number=6, + message=gcd_audio_config.OutputAudioConfig, + ) + + +class StreamingRecognitionResult(proto.Message): + r"""Contains a speech recognition result corresponding to a portion of + the audio that is currently being processed or an indication that + this is the end of the single requested utterance. + + While end-user audio is being processed, Dialogflow sends a series + of results. Each result may contain a ``transcript`` value. A + transcript represents a portion of the utterance. While the + recognizer is processing audio, transcript values may be interim + values or finalized values. Once a transcript is finalized, the + ``is_final`` value is set to true and processing continues for the + next transcript. + + If + ``StreamingDetectIntentRequest.query_input.audio_config.single_utterance`` + was true, and the recognizer has completed processing audio, the + ``message_type`` value is set to \`END_OF_SINGLE_UTTERANCE and the + following (last) result contains the last finalized transcript. + + The complete end-user utterance is determined by concatenating the + finalized transcript values received for the series of results. + + In the following example, single utterance is enabled. In the case + where single utterance is not enabled, result 7 would not occur. + + :: + + Num | transcript | message_type | is_final + --- | ----------------------- | ----------------------- | -------- + 1 | "tube" | TRANSCRIPT | false + 2 | "to be a" | TRANSCRIPT | false + 3 | "to be" | TRANSCRIPT | false + 4 | "to be or not to be" | TRANSCRIPT | true + 5 | "that's" | TRANSCRIPT | false + 6 | "that is | TRANSCRIPT | false + 7 | unset | END_OF_SINGLE_UTTERANCE | unset + 8 | " that is the question" | TRANSCRIPT | true + + Concatenating the finalized transcripts with ``is_final`` set to + true, the complete utterance becomes "to be or not to be that is the + question". + + Attributes: + message_type (google.cloud.dialogflow_v2beta1.types.StreamingRecognitionResult.MessageType): + Type of the result message. + transcript (str): + Transcript text representing the words that the user spoke. + Populated if and only if ``message_type`` = ``TRANSCRIPT``. + is_final (bool): + If ``false``, the ``StreamingRecognitionResult`` represents + an interim result that may change. If ``true``, the + recognizer will not return any further hypotheses about this + piece of the audio. May only be populated for + ``message_type`` = ``TRANSCRIPT``. + confidence (float): + The Speech confidence between 0.0 and 1.0 for the current + portion of audio. A higher number indicates an estimated + greater likelihood that the recognized words are correct. + The default of 0.0 is a sentinel value indicating that + confidence was not set. + + This field is typically only provided if ``is_final`` is + true and you should not rely on it being accurate or even + set. + stability (float): + An estimate of the likelihood that the speech recognizer + will not change its guess about this interim recognition + result: + + - If the value is unspecified or 0.0, Dialogflow didn't + compute the stability. In particular, Dialogflow will + only provide stability for ``TRANSCRIPT`` results with + ``is_final = false``. + - Otherwise, the value is in (0.0, 1.0] where 0.0 means + completely unstable and 1.0 means completely stable. + speech_word_info (Sequence[google.cloud.dialogflow_v2beta1.types.SpeechWordInfo]): + Word-specific information for the words recognized by Speech + in + [transcript][google.cloud.dialogflow.v2beta1.StreamingRecognitionResult.transcript]. + Populated if and only if ``message_type`` = ``TRANSCRIPT`` + and [InputAudioConfig.enable_word_info] is set. + speech_end_offset (google.protobuf.duration_pb2.Duration): + Time offset of the end of this Speech recognition result + relative to the beginning of the audio. Only populated for + ``message_type`` = ``TRANSCRIPT``. + language_code (str): + Detected language code for the transcript. + dtmf_digits (google.cloud.dialogflow_v2beta1.types.TelephonyDtmfEvents): + DTMF digits. Populated if and only if ``message_type`` = + ``DTMF_DIGITS``. + """ + class MessageType(proto.Enum): + r"""Type of the response message.""" + MESSAGE_TYPE_UNSPECIFIED = 0 + TRANSCRIPT = 1 + DTMF_DIGITS = 3 + END_OF_SINGLE_UTTERANCE = 2 + PARTIAL_DTMF_DIGITS = 4 + + message_type = proto.Field( + proto.ENUM, + number=1, + enum=MessageType, + ) + transcript = proto.Field( + proto.STRING, + number=2, + ) + is_final = proto.Field( + proto.BOOL, + number=3, + ) + confidence = proto.Field( + proto.FLOAT, + number=4, + ) + stability = proto.Field( + proto.FLOAT, + number=6, + ) + speech_word_info = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=gcd_audio_config.SpeechWordInfo, + ) + speech_end_offset = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) + language_code = proto.Field( + proto.STRING, + number=10, + ) + dtmf_digits = proto.Field( + proto.MESSAGE, + number=5, + message=gcd_audio_config.TelephonyDtmfEvents, + ) + + +class TextInput(proto.Message): + r"""Represents the natural language text to be processed. + + Attributes: + text (str): + Required. The UTF-8 encoded natural language + text to be processed. Text length must not + exceed 256 characters. + language_code (str): + Required. The language of this conversational query. See + `Language + Support `__ + for a list of the currently supported language codes. Note + that queries in the same session do not necessarily need to + specify the same language. + """ + + text = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class EventInput(proto.Message): + r"""Events allow for matching intents by event name instead of the + natural language input. For instance, input + ```` + can trigger a personalized welcome response. The parameter ``name`` + may be used by the agent in the response: + ``"Hello #welcome_event.name! What can I do for you today?"``. + + Attributes: + name (str): + Required. The unique identifier of the event. + parameters (google.protobuf.struct_pb2.Struct): + The collection of parameters associated with + the event. + Depending on your protocol or client library + language, this is a map, associative array, + symbol table, dictionary, or JSON object + composed of a collection of (MapKey, MapValue) + pairs: + - MapKey type: string + - MapKey value: parameter name + - MapValue type: + - If parameter's entity type is a + composite entity: map - Else: depending on + parameter value type, could be one of string, + number, boolean, null, list or map + - MapValue value: + - If parameter's entity type is a + composite entity: map from composite + entity property names to property values - + Else: parameter value + language_code (str): + Required. The language of this query. See `Language + Support `__ + for a list of the currently supported language codes. Note + that queries in the same session do not necessarily need to + specify the same language. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + parameters = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class SentimentAnalysisRequestConfig(proto.Message): + r"""Configures the types of sentiment analysis to perform. + + Attributes: + analyze_query_text_sentiment (bool): + Instructs the service to perform sentiment analysis on + ``query_text``. If not provided, sentiment analysis is not + performed on ``query_text``. + """ + + analyze_query_text_sentiment = proto.Field( + proto.BOOL, + number=1, + ) + + +class SentimentAnalysisResult(proto.Message): + r"""The result of sentiment analysis. Sentiment analysis inspects user + input and identifies the prevailing subjective opinion, especially + to determine a user's attitude as positive, negative, or neutral. + For [Participants.DetectIntent][], it needs to be configured in + [DetectIntentRequest.query_params][google.cloud.dialogflow.v2beta1.DetectIntentRequest.query_params]. + For [Participants.StreamingDetectIntent][], it needs to be + configured in + [StreamingDetectIntentRequest.query_params][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_params]. + And for + [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent] + and + [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.StreamingAnalyzeContent], + it needs to be configured in + [ConversationProfile.human_agent_assistant_config][google.cloud.dialogflow.v2beta1.ConversationProfile.human_agent_assistant_config] + + Attributes: + query_text_sentiment (google.cloud.dialogflow_v2beta1.types.Sentiment): + The sentiment analysis result for ``query_text``. + """ + + query_text_sentiment = proto.Field( + proto.MESSAGE, + number=1, + message='Sentiment', + ) + + +class Sentiment(proto.Message): + r"""The sentiment, such as positive/negative feeling or + association, for a unit of analysis, such as the query text. + + Attributes: + score (float): + Sentiment score between -1.0 (negative + sentiment) and 1.0 (positive sentiment). + magnitude (float): + A non-negative number in the [0, +inf) range, which + represents the absolute magnitude of sentiment, regardless + of score (positive or negative). + """ + + score = proto.Field( + proto.FLOAT, + number=1, + ) + magnitude = proto.Field( + proto.FLOAT, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/session_entity_type.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/session_entity_type.py new file mode 100644 index 000000000..4442b9004 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/session_entity_type.py @@ -0,0 +1,274 @@ +# -*- 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.dialogflow_v2beta1.types import entity_type +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2beta1', + manifest={ + 'SessionEntityType', + 'ListSessionEntityTypesRequest', + 'ListSessionEntityTypesResponse', + 'GetSessionEntityTypeRequest', + 'CreateSessionEntityTypeRequest', + 'UpdateSessionEntityTypeRequest', + 'DeleteSessionEntityTypeRequest', + }, +) + + +class SessionEntityType(proto.Message): + r"""A session represents a conversation between a Dialogflow agent and + an end-user. You can create special entities, called session + entities, during a session. Session entities can extend or replace + custom entity types and only exist during the session that they were + created for. All session data, including session entities, is stored + by Dialogflow for 20 minutes. + + For more information, see the `session entity + guide `__. + + Attributes: + name (str): + Required. The unique identifier of this session entity type. + Supported formats: + + - ``projects//agent/sessions//entityTypes/`` + - ``projects//locations//agent/sessions//entityTypes/`` + - ``projects//agent/environments//users//sessions//entityTypes/`` + - ``projects//locations//agent/environments/ /users//sessions//entityTypes/`` + + If ``Location ID`` is not specified we assume default 'us' + location. If ``Environment ID`` is not specified, we assume + default 'draft' environment. If ``User ID`` is not + specified, we assume default '-' user. + ```` must be the display name of + an existing entity type in the same agent that will be + overridden or supplemented. + entity_override_mode (google.cloud.dialogflow_v2beta1.types.SessionEntityType.EntityOverrideMode): + Required. Indicates whether the additional + data should override or supplement the custom + entity type definition. + entities (Sequence[google.cloud.dialogflow_v2beta1.types.EntityType.Entity]): + Required. The collection of entities + associated with this session entity type. + """ + class EntityOverrideMode(proto.Enum): + r"""The types of modifications for a session entity type.""" + ENTITY_OVERRIDE_MODE_UNSPECIFIED = 0 + ENTITY_OVERRIDE_MODE_OVERRIDE = 1 + ENTITY_OVERRIDE_MODE_SUPPLEMENT = 2 + + name = proto.Field( + proto.STRING, + number=1, + ) + entity_override_mode = proto.Field( + proto.ENUM, + number=2, + enum=EntityOverrideMode, + ) + entities = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=entity_type.EntityType.Entity, + ) + + +class ListSessionEntityTypesRequest(proto.Message): + r"""The request message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2beta1.SessionEntityTypes.ListSessionEntityTypes]. + + Attributes: + parent (str): + Required. The session to list all session entity types from. + Supported formats: + + - \`projects//agent/sessions/, + - ``projects//locations//agent/sessions/``, + - ``projects//agent/environments//users//sessions/``, + - ``projects//locations//agent/environments//users//sessions/``, + + If ``Location ID`` is not specified we assume default 'us' + location. If ``Environment ID`` is not specified, we assume + default 'draft' environment. If ``User ID`` is not + specified, we assume default '-' user. + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListSessionEntityTypesResponse(proto.Message): + r"""The response message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2beta1.SessionEntityTypes.ListSessionEntityTypes]. + + Attributes: + session_entity_types (Sequence[google.cloud.dialogflow_v2beta1.types.SessionEntityType]): + The list of session entity types. There will be a maximum + number of items returned based on the page_size field in the + request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + session_entity_types = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SessionEntityType', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetSessionEntityTypeRequest(proto.Message): + r"""The request message for + [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.GetSessionEntityType]. + + Attributes: + name (str): + Required. The name of the session entity type. Supported + formats: + + - ``projects//agent/sessions//entityTypes/`` + - ``projects//locations//agent/sessions//entityTypes/`` + - ``projects//agent/environments//users//sessions//entityTypes/`` + - ``projects//locations//agent/environments/ /users//sessions//entityTypes/`` + + If ``Location ID`` is not specified we assume default 'us' + location. If ``Environment ID`` is not specified, we assume + default 'draft' environment. If ``User ID`` is not + specified, we assume default '-' user. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateSessionEntityTypeRequest(proto.Message): + r"""The request message for + [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.CreateSessionEntityType]. + + Attributes: + parent (str): + Required. The session to create a session entity type for. + Supported formats: + + - \`projects//agent/sessions/, + - ``projects//locations//agent/sessions/``, + - ``projects//agent/environments//users//sessions/``, + - ``projects//locations//agent/environments//users//sessions/``, + + If ``Location ID`` is not specified we assume default 'us' + location. If ``Environment ID`` is not specified, we assume + default 'draft' environment. If ``User ID`` is not + specified, we assume default '-' user. + session_entity_type (google.cloud.dialogflow_v2beta1.types.SessionEntityType): + Required. The session entity type to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + session_entity_type = proto.Field( + proto.MESSAGE, + number=2, + message='SessionEntityType', + ) + + +class UpdateSessionEntityTypeRequest(proto.Message): + r"""The request message for + [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.UpdateSessionEntityType]. + + Attributes: + session_entity_type (google.cloud.dialogflow_v2beta1.types.SessionEntityType): + Required. The session entity type to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which fields + get updated. + """ + + session_entity_type = proto.Field( + proto.MESSAGE, + number=1, + message='SessionEntityType', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteSessionEntityTypeRequest(proto.Message): + r"""The request message for + [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.DeleteSessionEntityType]. + + Attributes: + name (str): + Required. The name of the entity type to delete. Supported + formats: + + - ``projects//agent/sessions//entityTypes/`` + - ``projects//locations//agent/sessions//entityTypes/`` + - ``projects//agent/environments//users//sessions//entityTypes/`` + - ``projects//locations//agent/environments/ /users//sessions//entityTypes/`` + + If ``Location ID`` is not specified we assume default 'us' + location. If ``Environment ID`` is not specified, we assume + default 'draft' environment. If ``User ID`` is not + specified, we assume default '-' user. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/validation_result.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/validation_result.py new file mode 100644 index 000000000..399c95f52 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/validation_result.py @@ -0,0 +1,95 @@ +# -*- 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.dialogflow.v2beta1', + manifest={ + 'ValidationError', + 'ValidationResult', + }, +) + + +class ValidationError(proto.Message): + r"""Represents a single validation error. + + Attributes: + severity (google.cloud.dialogflow_v2beta1.types.ValidationError.Severity): + The severity of the error. + entries (Sequence[str]): + The names of the entries that the error is + associated with. Format: + + - "projects//agent", if the error is + associated with the entire agent. + - "projects//agent/intents/", if the error is associated with certain + intents. + - "projects//agent/intents//trainingPhrases/", if + the error is associated with certain intent + training phrases. - "projects//agent/intents//parameters/", if the error is + associated with certain intent parameters. - + "projects//agent/entities/", if the error is associated with certain + entities. + error_message (str): + The detailed error message. + """ + class Severity(proto.Enum): + r"""Represents a level of severity.""" + SEVERITY_UNSPECIFIED = 0 + INFO = 1 + WARNING = 2 + ERROR = 3 + CRITICAL = 4 + + severity = proto.Field( + proto.ENUM, + number=1, + enum=Severity, + ) + entries = proto.RepeatedField( + proto.STRING, + number=3, + ) + error_message = proto.Field( + proto.STRING, + number=4, + ) + + +class ValidationResult(proto.Message): + r"""Represents the output of agent validation. + + Attributes: + validation_errors (Sequence[google.cloud.dialogflow_v2beta1.types.ValidationError]): + Contains all validation errors. + """ + + validation_errors = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ValidationError', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/version.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/version.py new file mode 100644 index 000000000..c1795217f --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/version.py @@ -0,0 +1,265 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2beta1', + manifest={ + 'Version', + 'ListVersionsRequest', + 'ListVersionsResponse', + 'GetVersionRequest', + 'CreateVersionRequest', + 'UpdateVersionRequest', + 'DeleteVersionRequest', + }, +) + + +class Version(proto.Message): + r"""You can create multiple versions of your agent and publish them to + separate environments. + + When you edit an agent, you are editing the draft agent. At any + point, you can save the draft agent as an agent version, which is an + immutable snapshot of your agent. + + When you save the draft agent, it is published to the default + environment. When you create agent versions, you can publish them to + custom environments. You can create a variety of custom environments + for: + + - testing + - development + - production + - etc. + + For more information, see the `versions and environments + guide `__. + + Attributes: + name (str): + Output only. The unique identifier of this agent version. + Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + description (str): + Optional. The developer-provided description + of this version. + version_number (int): + Output only. The sequential number of this + version. This field is read-only which means it + cannot be set by create and update methods. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation time of this + version. This field is read-only, i.e., it + cannot be set by create and update methods. + status (google.cloud.dialogflow_v2beta1.types.Version.VersionStatus): + Output only. The status of this version. This + field is read-only and cannot be set by create + and update methods. + """ + class VersionStatus(proto.Enum): + r"""The status of a version.""" + VERSION_STATUS_UNSPECIFIED = 0 + IN_PROGRESS = 1 + READY = 2 + FAILED = 3 + + name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + version_number = proto.Field( + proto.INT32, + number=3, + ) + create_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + status = proto.Field( + proto.ENUM, + number=6, + enum=VersionStatus, + ) + + +class ListVersionsRequest(proto.Message): + r"""The request message for + [Versions.ListVersions][google.cloud.dialogflow.v2beta1.Versions.ListVersions]. + + Attributes: + parent (str): + Required. The agent to list all versions from. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListVersionsResponse(proto.Message): + r"""The response message for + [Versions.ListVersions][google.cloud.dialogflow.v2beta1.Versions.ListVersions]. + + Attributes: + versions (Sequence[google.cloud.dialogflow_v2beta1.types.Version]): + The list of agent versions. There will be a maximum number + of items returned based on the page_size field in the + request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + versions = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Version', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetVersionRequest(proto.Message): + r"""The request message for + [Versions.GetVersion][google.cloud.dialogflow.v2beta1.Versions.GetVersion]. + + Attributes: + name (str): + Required. The name of the version. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateVersionRequest(proto.Message): + r"""The request message for + [Versions.CreateVersion][google.cloud.dialogflow.v2beta1.Versions.CreateVersion]. + + Attributes: + parent (str): + Required. The agent to create a version for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + version (google.cloud.dialogflow_v2beta1.types.Version): + Required. The version to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + version = proto.Field( + proto.MESSAGE, + number=2, + message='Version', + ) + + +class UpdateVersionRequest(proto.Message): + r"""The request message for + [Versions.UpdateVersion][google.cloud.dialogflow.v2beta1.Versions.UpdateVersion]. + + Attributes: + version (google.cloud.dialogflow_v2beta1.types.Version): + Required. The version to update. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. + """ + + version = proto.Field( + proto.MESSAGE, + number=1, + message='Version', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteVersionRequest(proto.Message): + r"""The request message for + [Versions.DeleteVersion][google.cloud.dialogflow.v2beta1.Versions.DeleteVersion]. + + Attributes: + name (str): + Required. The name of the version to delete. Supported + formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/webhook.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/webhook.py new file mode 100644 index 000000000..16d166bf8 --- /dev/null +++ b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/webhook.py @@ -0,0 +1,261 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.dialogflow_v2beta1.types import context +from google.cloud.dialogflow_v2beta1.types import intent +from google.cloud.dialogflow_v2beta1.types import session as gcd_session +from google.cloud.dialogflow_v2beta1.types import session_entity_type +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.v2beta1', + manifest={ + 'WebhookRequest', + 'WebhookResponse', + 'OriginalDetectIntentRequest', + }, +) + + +class WebhookRequest(proto.Message): + r"""The request message for a webhook call. + + Attributes: + session (str): + The unique identifier of detectIntent request session. Can + be used to identify end-user inside webhook implementation. + Supported formats: + + - \`projects//agent/sessions/, + - ``projects//locations//agent/sessions/``, + - ``projects//agent/environments//users//sessions/``, + - ``projects//locations//agent/environments//users//sessions/``, + response_id (str): + The unique identifier of the response. Contains the same + value as ``[Streaming]DetectIntentResponse.response_id``. + query_result (google.cloud.dialogflow_v2beta1.types.QueryResult): + The result of the conversational query or event processing. + Contains the same value as + ``[Streaming]DetectIntentResponse.query_result``. + alternative_query_results (Sequence[google.cloud.dialogflow_v2beta1.types.QueryResult]): + Alternative query results from + KnowledgeService. + original_detect_intent_request (google.cloud.dialogflow_v2beta1.types.OriginalDetectIntentRequest): + Optional. The contents of the original request that was + passed to ``[Streaming]DetectIntent`` call. + """ + + session = proto.Field( + proto.STRING, + number=4, + ) + response_id = proto.Field( + proto.STRING, + number=1, + ) + query_result = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_session.QueryResult, + ) + alternative_query_results = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=gcd_session.QueryResult, + ) + original_detect_intent_request = proto.Field( + proto.MESSAGE, + number=3, + message='OriginalDetectIntentRequest', + ) + + +class WebhookResponse(proto.Message): + r"""The response message for a webhook call. + + This response is validated by the Dialogflow server. If validation + fails, an error will be returned in the + [QueryResult.diagnostic_info][google.cloud.dialogflow.v2beta1.QueryResult.diagnostic_info] + field. Setting JSON fields to an empty value with the wrong type is + a common error. To avoid this error: + + - Use ``""`` for empty strings + - Use ``{}`` or ``null`` for empty objects + - Use ``[]`` or ``null`` for empty arrays + + For more information, see the `Protocol Buffers Language + Guide `__. + + Attributes: + fulfillment_text (str): + Optional. The text response message intended for the + end-user. It is recommended to use + ``fulfillment_messages.text.text[0]`` instead. When + provided, Dialogflow uses this field to populate + [QueryResult.fulfillment_text][google.cloud.dialogflow.v2beta1.QueryResult.fulfillment_text] + sent to the integration or API caller. + fulfillment_messages (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message]): + Optional. The rich response messages intended for the + end-user. When provided, Dialogflow uses this field to + populate + [QueryResult.fulfillment_messages][google.cloud.dialogflow.v2beta1.QueryResult.fulfillment_messages] + sent to the integration or API caller. + source (str): + Optional. A custom field used to identify the webhook + source. Arbitrary strings are supported. When provided, + Dialogflow uses this field to populate + [QueryResult.webhook_source][google.cloud.dialogflow.v2beta1.QueryResult.webhook_source] + sent to the integration or API caller. + payload (google.protobuf.struct_pb2.Struct): + Optional. This field can be used to pass custom data from + your webhook to the integration or API caller. Arbitrary + JSON objects are supported. When provided, Dialogflow uses + this field to populate + [QueryResult.webhook_payload][google.cloud.dialogflow.v2beta1.QueryResult.webhook_payload] + sent to the integration or API caller. This field is also + used by the `Google Assistant + integration `__ + for rich response messages. See the format definition at + `Google Assistant Dialogflow webhook + format `__ + output_contexts (Sequence[google.cloud.dialogflow_v2beta1.types.Context]): + Optional. The collection of output contexts that will + overwrite currently active contexts for the session and + reset their lifespans. When provided, Dialogflow uses this + field to populate + [QueryResult.output_contexts][google.cloud.dialogflow.v2beta1.QueryResult.output_contexts] + sent to the integration or API caller. + followup_event_input (google.cloud.dialogflow_v2beta1.types.EventInput): + Optional. Invokes the supplied events. When this field is + set, Dialogflow ignores the ``fulfillment_text``, + ``fulfillment_messages``, and ``payload`` fields. + live_agent_handoff (bool): + Indicates that a live agent should be brought in to handle + the interaction with the user. In most cases, when you set + this flag to true, you would also want to set + end_interaction to true as well. Default is false. + end_interaction (bool): + Optional. Indicates that this intent ends an + interaction. Some integrations (e.g., Actions on + Google or Dialogflow phone gateway) use this + information to close interaction with an end + user. Default is false. + session_entity_types (Sequence[google.cloud.dialogflow_v2beta1.types.SessionEntityType]): + Optional. Additional session entity types to replace or + extend developer entity types with. The entity synonyms + apply to all languages and persist for the session. Setting + this data from a webhook overwrites the session entity types + that have been set using ``detectIntent``, + ``streamingDetectIntent`` or + [SessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityType] + management methods. + """ + + fulfillment_text = proto.Field( + proto.STRING, + number=1, + ) + fulfillment_messages = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=intent.Intent.Message, + ) + source = proto.Field( + proto.STRING, + number=3, + ) + payload = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Struct, + ) + output_contexts = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=context.Context, + ) + followup_event_input = proto.Field( + proto.MESSAGE, + number=6, + message=gcd_session.EventInput, + ) + live_agent_handoff = proto.Field( + proto.BOOL, + number=7, + ) + end_interaction = proto.Field( + proto.BOOL, + number=8, + ) + session_entity_types = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=session_entity_type.SessionEntityType, + ) + + +class OriginalDetectIntentRequest(proto.Message): + r"""Represents the contents of the original request that was passed to + the ``[Streaming]DetectIntent`` call. + + Attributes: + source (str): + The source of this request, e.g., ``google``, ``facebook``, + ``slack``. It is set by Dialogflow-owned servers. + version (str): + Optional. The version of the protocol used + for this request. This field is AoG-specific. + payload (google.protobuf.struct_pb2.Struct): + Optional. This field is set to the value of the + ``QueryParameters.payload`` field passed in the request. + Some integrations that query a Dialogflow agent may provide + additional information in the payload. + + In particular, for the Dialogflow Phone Gateway integration, + this field has the form: + + .. raw:: html + +
{
+                 "telephony": {
+                   "caller_id": "+18558363987"
+                 }
+                }
+ + Note: The caller ID field (``caller_id``) will be redacted + for Trial Edition agents and populated with the caller ID in + `E.164 format `__ for + Essentials Edition agents. + """ + + source = proto.Field( + proto.STRING, + number=1, + ) + version = proto.Field( + proto.STRING, + number=2, + ) + payload = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/mypy.ini b/owl-bot-staging/v2beta1/mypy.ini new file mode 100644 index 000000000..4505b4854 --- /dev/null +++ b/owl-bot-staging/v2beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v2beta1/noxfile.py b/owl-bot-staging/v2beta1/noxfile.py new file mode 100644 index 000000000..1e800f25f --- /dev/null +++ b/owl-bot-staging/v2beta1/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', '3.10']) +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/dialogflow_v2beta1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.9') +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', '3.8', '3.9']) +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.9') +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/v2beta1/scripts/fixup_dialogflow_v2beta1_keywords.py b/owl-bot-staging/v2beta1/scripts/fixup_dialogflow_v2beta1_keywords.py new file mode 100644 index 000000000..a921e3c51 --- /dev/null +++ b/owl-bot-staging/v2beta1/scripts/fixup_dialogflow_v2beta1_keywords.py @@ -0,0 +1,263 @@ +#! /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 dialogflowCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'analyze_content': ('participant', 'text_input', 'event_input', 'reply_audio_config', 'query_params', 'assist_query_params', 'message_send_time', 'request_id', ), + 'batch_create_entities': ('parent', 'entities', 'language_code', ), + 'batch_create_messages': ('parent', 'requests', ), + 'batch_delete_entities': ('parent', 'entity_values', 'language_code', ), + 'batch_delete_entity_types': ('parent', 'entity_type_names', ), + 'batch_delete_intents': ('parent', 'intents', ), + 'batch_update_entities': ('parent', 'entities', 'language_code', 'update_mask', ), + 'batch_update_entity_types': ('parent', 'entity_type_batch_uri', 'entity_type_batch_inline', 'language_code', 'update_mask', ), + 'batch_update_intents': ('parent', 'intent_batch_uri', 'intent_batch_inline', 'language_code', 'update_mask', 'intent_view', ), + 'compile_suggestion': ('parent', 'latest_message', 'context_size', ), + 'complete_conversation': ('name', ), + 'create_context': ('parent', 'context', ), + 'create_conversation': ('parent', 'conversation', 'conversation_id', ), + 'create_conversation_profile': ('parent', 'conversation_profile', ), + 'create_document': ('parent', 'document', 'import_gcs_custom_metadata', ), + 'create_entity_type': ('parent', 'entity_type', 'language_code', ), + 'create_environment': ('parent', 'environment', 'environment_id', ), + 'create_intent': ('parent', 'intent', 'language_code', 'intent_view', ), + 'create_knowledge_base': ('parent', 'knowledge_base', ), + 'create_participant': ('parent', 'participant', ), + 'create_session_entity_type': ('parent', 'session_entity_type', ), + 'create_version': ('parent', 'version', ), + 'delete_agent': ('parent', ), + 'delete_all_contexts': ('parent', ), + 'delete_context': ('name', ), + 'delete_conversation_profile': ('name', ), + 'delete_document': ('name', ), + 'delete_entity_type': ('name', ), + 'delete_environment': ('name', ), + 'delete_intent': ('name', ), + 'delete_knowledge_base': ('name', 'force', ), + 'delete_session_entity_type': ('name', ), + 'delete_version': ('name', ), + 'detect_intent': ('session', 'query_input', 'query_params', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), + 'export_agent': ('parent', 'agent_uri', ), + 'get_agent': ('parent', ), + 'get_answer_record': ('name', ), + 'get_context': ('name', ), + 'get_conversation': ('name', ), + 'get_conversation_profile': ('name', ), + 'get_document': ('name', ), + 'get_entity_type': ('name', 'language_code', ), + 'get_environment': ('name', ), + 'get_environment_history': ('parent', 'page_size', 'page_token', ), + 'get_fulfillment': ('name', ), + 'get_intent': ('name', 'language_code', 'intent_view', ), + 'get_knowledge_base': ('name', ), + 'get_participant': ('name', ), + 'get_session_entity_type': ('name', ), + 'get_validation_result': ('parent', 'language_code', ), + 'get_version': ('name', ), + 'import_agent': ('parent', 'agent_uri', 'agent_content', ), + 'import_documents': ('parent', 'document_template', 'gcs_source', 'import_gcs_custom_metadata', ), + 'list_answer_records': ('parent', 'page_size', 'page_token', ), + 'list_contexts': ('parent', 'page_size', 'page_token', ), + 'list_conversation_profiles': ('parent', 'page_size', 'page_token', ), + 'list_conversations': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_documents': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_entity_types': ('parent', 'language_code', 'page_size', 'page_token', ), + 'list_environments': ('parent', 'page_size', 'page_token', ), + 'list_intents': ('parent', 'language_code', 'intent_view', 'page_size', 'page_token', ), + 'list_knowledge_bases': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_messages': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_participants': ('parent', 'page_size', 'page_token', ), + 'list_session_entity_types': ('parent', 'page_size', 'page_token', ), + 'list_suggestions': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_versions': ('parent', 'page_size', 'page_token', ), + 'reload_document': ('name', 'gcs_source', 'import_gcs_custom_metadata', ), + 'restore_agent': ('parent', 'agent_uri', 'agent_content', ), + 'search_agents': ('parent', 'page_size', 'page_token', ), + 'set_agent': ('agent', 'update_mask', ), + 'streaming_detect_intent': ('session', 'query_input', 'query_params', 'single_utterance', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), + 'suggest_articles': ('parent', 'latest_message', 'context_size', 'assist_query_params', ), + 'suggest_faq_answers': ('parent', 'latest_message', 'context_size', 'assist_query_params', ), + 'suggest_smart_replies': ('parent', 'current_text_input', 'latest_message', 'context_size', ), + 'train_agent': ('parent', ), + 'update_answer_record': ('answer_record', 'update_mask', ), + 'update_context': ('context', 'update_mask', ), + 'update_conversation_profile': ('conversation_profile', 'update_mask', ), + 'update_document': ('document', 'update_mask', ), + 'update_entity_type': ('entity_type', 'language_code', 'update_mask', ), + 'update_environment': ('environment', 'update_mask', 'allow_load_to_draft_and_discard_changes', ), + 'update_fulfillment': ('fulfillment', 'update_mask', ), + 'update_intent': ('intent', 'language_code', 'update_mask', 'intent_view', ), + 'update_knowledge_base': ('knowledge_base', 'update_mask', ), + 'update_participant': ('participant', 'update_mask', ), + 'update_session_entity_type': ('session_entity_type', 'update_mask', ), + 'update_version': ('version', 'update_mask', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=dialogflowCallTransformer(), +): + """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 dialogflow 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/v2beta1/setup.py b/owl-bot-staging/v2beta1/setup.py new file mode 100644 index 000000000..5f320d08d --- /dev/null +++ b/owl-bot-staging/v2beta1/setup.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, 'README.rst') +with io.open(readme_filename, encoding='utf-8') as readme_file: + readme = readme_file.read() + +setuptools.setup( + name='google-cloud-dialogflow', + 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.28.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.19.7', + ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v2beta1/tests/__init__.py b/owl-bot-staging/v2beta1/tests/__init__.py new file mode 100644 index 000000000..b54a5fcc4 --- /dev/null +++ b/owl-bot-staging/v2beta1/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/v2beta1/tests/unit/__init__.py b/owl-bot-staging/v2beta1/tests/unit/__init__.py new file mode 100644 index 000000000..b54a5fcc4 --- /dev/null +++ b/owl-bot-staging/v2beta1/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/v2beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v2beta1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000..b54a5fcc4 --- /dev/null +++ b/owl-bot-staging/v2beta1/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/v2beta1/tests/unit/gapic/dialogflow_v2beta1/__init__.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/__init__.py new file mode 100644 index 000000000..b54a5fcc4 --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/__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/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_agents.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_agents.py new file mode 100644 index 000000000..d5146e386 --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_agents.py @@ -0,0 +1,3084 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.agents import AgentsAsyncClient +from google.cloud.dialogflow_v2beta1.services.agents import AgentsClient +from google.cloud.dialogflow_v2beta1.services.agents import pagers +from google.cloud.dialogflow_v2beta1.services.agents import transports +from google.cloud.dialogflow_v2beta1.types import agent +from google.cloud.dialogflow_v2beta1.types import agent as gcd_agent +from google.cloud.dialogflow_v2beta1.types import validation_result +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 struct_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert AgentsClient._get_default_mtls_endpoint(None) is None + assert AgentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AgentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AgentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AgentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AgentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + AgentsClient, + AgentsAsyncClient, +]) +def test_agents_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AgentsGrpcTransport, "grpc"), + (transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_agents_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + AgentsClient, + AgentsAsyncClient, +]) +def test_agents_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 == 'dialogflow.googleapis.com:443' + + +def test_agents_client_get_transport_class(): + transport = AgentsClient.get_transport_class() + available_transports = [ + transports.AgentsGrpcTransport, + ] + assert transport in available_transports + + transport = AgentsClient.get_transport_class("grpc") + assert transport == transports.AgentsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AgentsClient, transports.AgentsGrpcTransport, "grpc"), + (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(AgentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AgentsClient)) +@mock.patch.object(AgentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AgentsAsyncClient)) +def test_agents_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(AgentsClient, '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(AgentsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (AgentsClient, transports.AgentsGrpcTransport, "grpc", "true"), + (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AgentsClient, transports.AgentsGrpcTransport, "grpc", "false"), + (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(AgentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AgentsClient)) +@mock.patch.object(AgentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AgentsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_agents_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AgentsClient, transports.AgentsGrpcTransport, "grpc"), + (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_agents_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AgentsClient, transports.AgentsGrpcTransport, "grpc"), + (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_agents_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_agents_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2beta1.services.agents.transports.AgentsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AgentsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_get_agent(transport: str = 'grpc', request_type=agent.GetAgentRequest): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = agent.Agent( + parent='parent_value', + display_name='display_name_value', + default_language_code='default_language_code_value', + supported_language_codes=['supported_language_codes_value'], + time_zone='time_zone_value', + description='description_value', + avatar_uri='avatar_uri_value', + enable_logging=True, + match_mode=agent.Agent.MatchMode.MATCH_MODE_HYBRID, + classification_threshold=0.25520000000000004, + api_version=agent.Agent.ApiVersion.API_VERSION_V1, + tier=agent.Agent.Tier.TIER_STANDARD, + ) + response = client.get_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, agent.Agent) + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.default_language_code == 'default_language_code_value' + assert response.supported_language_codes == ['supported_language_codes_value'] + assert response.time_zone == 'time_zone_value' + assert response.description == 'description_value' + assert response.avatar_uri == 'avatar_uri_value' + assert response.enable_logging is True + assert response.match_mode == agent.Agent.MatchMode.MATCH_MODE_HYBRID + assert math.isclose(response.classification_threshold, 0.25520000000000004, rel_tol=1e-6) + assert response.api_version == agent.Agent.ApiVersion.API_VERSION_V1 + assert response.tier == agent.Agent.Tier.TIER_STANDARD + + +def test_get_agent_from_dict(): + test_get_agent(request_type=dict) + + +def test_get_agent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=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_agent), + '__call__') as call: + client.get_agent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetAgentRequest() + + +@pytest.mark.asyncio +async def test_get_agent_async(transport: str = 'grpc_asyncio', request_type=agent.GetAgentRequest): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(agent.Agent( + parent='parent_value', + display_name='display_name_value', + default_language_code='default_language_code_value', + supported_language_codes=['supported_language_codes_value'], + time_zone='time_zone_value', + description='description_value', + avatar_uri='avatar_uri_value', + enable_logging=True, + match_mode=agent.Agent.MatchMode.MATCH_MODE_HYBRID, + classification_threshold=0.25520000000000004, + api_version=agent.Agent.ApiVersion.API_VERSION_V1, + tier=agent.Agent.Tier.TIER_STANDARD, + )) + response = await client.get_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, agent.Agent) + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.default_language_code == 'default_language_code_value' + assert response.supported_language_codes == ['supported_language_codes_value'] + assert response.time_zone == 'time_zone_value' + assert response.description == 'description_value' + assert response.avatar_uri == 'avatar_uri_value' + assert response.enable_logging is True + assert response.match_mode == agent.Agent.MatchMode.MATCH_MODE_HYBRID + assert math.isclose(response.classification_threshold, 0.25520000000000004, rel_tol=1e-6) + assert response.api_version == agent.Agent.ApiVersion.API_VERSION_V1 + assert response.tier == agent.Agent.Tier.TIER_STANDARD + + +@pytest.mark.asyncio +async def test_get_agent_async_from_dict(): + await test_get_agent_async(request_type=dict) + + +def test_get_agent_field_headers(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.GetAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_agent), + '__call__') as call: + call.return_value = agent.Agent() + client.get_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_get_agent_field_headers_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.GetAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_agent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.Agent()) + await client.get_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_get_agent_flattened(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = agent.Agent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_agent( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_get_agent_flattened_error(): + client = AgentsClient( + credentials=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_agent( + agent.GetAgentRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_get_agent_flattened_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = agent.Agent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.Agent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_agent( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_agent_flattened_error_async(): + client = AgentsAsyncClient( + credentials=ga_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_agent( + agent.GetAgentRequest(), + parent='parent_value', + ) + + +def test_set_agent(transport: str = 'grpc', request_type=gcd_agent.SetAgentRequest): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_agent.Agent( + parent='parent_value', + display_name='display_name_value', + default_language_code='default_language_code_value', + supported_language_codes=['supported_language_codes_value'], + time_zone='time_zone_value', + description='description_value', + avatar_uri='avatar_uri_value', + enable_logging=True, + match_mode=gcd_agent.Agent.MatchMode.MATCH_MODE_HYBRID, + classification_threshold=0.25520000000000004, + api_version=gcd_agent.Agent.ApiVersion.API_VERSION_V1, + tier=gcd_agent.Agent.Tier.TIER_STANDARD, + ) + response = client.set_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_agent.SetAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_agent.Agent) + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.default_language_code == 'default_language_code_value' + assert response.supported_language_codes == ['supported_language_codes_value'] + assert response.time_zone == 'time_zone_value' + assert response.description == 'description_value' + assert response.avatar_uri == 'avatar_uri_value' + assert response.enable_logging is True + assert response.match_mode == gcd_agent.Agent.MatchMode.MATCH_MODE_HYBRID + assert math.isclose(response.classification_threshold, 0.25520000000000004, rel_tol=1e-6) + assert response.api_version == gcd_agent.Agent.ApiVersion.API_VERSION_V1 + assert response.tier == gcd_agent.Agent.Tier.TIER_STANDARD + + +def test_set_agent_from_dict(): + test_set_agent(request_type=dict) + + +def test_set_agent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent), + '__call__') as call: + client.set_agent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_agent.SetAgentRequest() + + +@pytest.mark.asyncio +async def test_set_agent_async(transport: str = 'grpc_asyncio', request_type=gcd_agent.SetAgentRequest): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_agent.Agent( + parent='parent_value', + display_name='display_name_value', + default_language_code='default_language_code_value', + supported_language_codes=['supported_language_codes_value'], + time_zone='time_zone_value', + description='description_value', + avatar_uri='avatar_uri_value', + enable_logging=True, + match_mode=gcd_agent.Agent.MatchMode.MATCH_MODE_HYBRID, + classification_threshold=0.25520000000000004, + api_version=gcd_agent.Agent.ApiVersion.API_VERSION_V1, + tier=gcd_agent.Agent.Tier.TIER_STANDARD, + )) + response = await client.set_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_agent.SetAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_agent.Agent) + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.default_language_code == 'default_language_code_value' + assert response.supported_language_codes == ['supported_language_codes_value'] + assert response.time_zone == 'time_zone_value' + assert response.description == 'description_value' + assert response.avatar_uri == 'avatar_uri_value' + assert response.enable_logging is True + assert response.match_mode == gcd_agent.Agent.MatchMode.MATCH_MODE_HYBRID + assert math.isclose(response.classification_threshold, 0.25520000000000004, rel_tol=1e-6) + assert response.api_version == gcd_agent.Agent.ApiVersion.API_VERSION_V1 + assert response.tier == gcd_agent.Agent.Tier.TIER_STANDARD + + +@pytest.mark.asyncio +async def test_set_agent_async_from_dict(): + await test_set_agent_async(request_type=dict) + + +def test_set_agent_field_headers(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_agent.SetAgentRequest() + + request.agent.parent = 'agent.parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent), + '__call__') as call: + call.return_value = gcd_agent.Agent() + client.set_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'agent.parent=agent.parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_agent_field_headers_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_agent.SetAgentRequest() + + request.agent.parent = 'agent.parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_agent.Agent()) + await client.set_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'agent.parent=agent.parent/value', + ) in kw['metadata'] + + +def test_set_agent_flattened(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_agent.Agent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_agent( + agent=gcd_agent.Agent(parent='parent_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].agent + mock_val = gcd_agent.Agent(parent='parent_value') + assert arg == mock_val + + +def test_set_agent_flattened_error(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_agent( + gcd_agent.SetAgentRequest(), + agent=gcd_agent.Agent(parent='parent_value'), + ) + + +@pytest.mark.asyncio +async def test_set_agent_flattened_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_agent.Agent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_agent.Agent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_agent( + agent=gcd_agent.Agent(parent='parent_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].agent + mock_val = gcd_agent.Agent(parent='parent_value') + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_set_agent_flattened_error_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_agent( + gcd_agent.SetAgentRequest(), + agent=gcd_agent.Agent(parent='parent_value'), + ) + + +def test_delete_agent(transport: str = 'grpc', request_type=agent.DeleteAgentRequest): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.DeleteAgentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_agent_from_dict(): + test_delete_agent(request_type=dict) + + +def test_delete_agent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=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_agent), + '__call__') as call: + client.delete_agent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent.DeleteAgentRequest() + + +@pytest.mark.asyncio +async def test_delete_agent_async(transport: str = 'grpc_asyncio', request_type=agent.DeleteAgentRequest): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == agent.DeleteAgentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_agent_async_from_dict(): + await test_delete_agent_async(request_type=dict) + + +def test_delete_agent_field_headers(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.DeleteAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_agent), + '__call__') as call: + call.return_value = None + client.delete_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_delete_agent_field_headers_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.DeleteAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_agent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_delete_agent_flattened(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_agent), + '__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_agent( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_delete_agent_flattened_error(): + client = AgentsClient( + credentials=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_agent( + agent.DeleteAgentRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_delete_agent_flattened_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_agent), + '__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_agent( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_agent_flattened_error_async(): + client = AgentsAsyncClient( + credentials=ga_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_agent( + agent.DeleteAgentRequest(), + parent='parent_value', + ) + + +def test_search_agents(transport: str = 'grpc', request_type=agent.SearchAgentsRequest): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_agents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = agent.SearchAgentsResponse( + next_page_token='next_page_token_value', + ) + response = client.search_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.SearchAgentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAgentsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_search_agents_from_dict(): + test_search_agents(request_type=dict) + + +def test_search_agents_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_agents), + '__call__') as call: + client.search_agents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent.SearchAgentsRequest() + + +@pytest.mark.asyncio +async def test_search_agents_async(transport: str = 'grpc_asyncio', request_type=agent.SearchAgentsRequest): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_agents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(agent.SearchAgentsResponse( + next_page_token='next_page_token_value', + )) + response = await client.search_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == agent.SearchAgentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAgentsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_search_agents_async_from_dict(): + await test_search_agents_async(request_type=dict) + + +def test_search_agents_field_headers(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.SearchAgentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_agents), + '__call__') as call: + call.return_value = agent.SearchAgentsResponse() + client.search_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_search_agents_field_headers_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.SearchAgentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_agents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.SearchAgentsResponse()) + await client.search_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_search_agents_flattened(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_agents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = agent.SearchAgentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.search_agents( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_search_agents_flattened_error(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.search_agents( + agent.SearchAgentsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_search_agents_flattened_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_agents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = agent.SearchAgentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.SearchAgentsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.search_agents( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_search_agents_flattened_error_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.search_agents( + agent.SearchAgentsRequest(), + parent='parent_value', + ) + + +def test_search_agents_pager(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_agents), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + agent.SearchAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + agent.Agent(), + ], + next_page_token='abc', + ), + agent.SearchAgentsResponse( + agents=[], + next_page_token='def', + ), + agent.SearchAgentsResponse( + agents=[ + agent.Agent(), + ], + next_page_token='ghi', + ), + agent.SearchAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.search_agents(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, agent.Agent) + for i in results) + +def test_search_agents_pages(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_agents), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + agent.SearchAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + agent.Agent(), + ], + next_page_token='abc', + ), + agent.SearchAgentsResponse( + agents=[], + next_page_token='def', + ), + agent.SearchAgentsResponse( + agents=[ + agent.Agent(), + ], + next_page_token='ghi', + ), + agent.SearchAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + ], + ), + RuntimeError, + ) + pages = list(client.search_agents(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_search_agents_async_pager(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_agents), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent.SearchAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + agent.Agent(), + ], + next_page_token='abc', + ), + agent.SearchAgentsResponse( + agents=[], + next_page_token='def', + ), + agent.SearchAgentsResponse( + agents=[ + agent.Agent(), + ], + next_page_token='ghi', + ), + agent.SearchAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + ], + ), + RuntimeError, + ) + async_pager = await client.search_agents(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, agent.Agent) + for i in responses) + +@pytest.mark.asyncio +async def test_search_agents_async_pages(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_agents), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent.SearchAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + agent.Agent(), + ], + next_page_token='abc', + ), + agent.SearchAgentsResponse( + agents=[], + next_page_token='def', + ), + agent.SearchAgentsResponse( + agents=[ + agent.Agent(), + ], + next_page_token='ghi', + ), + agent.SearchAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.search_agents(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_train_agent(transport: str = 'grpc', request_type=agent.TrainAgentRequest): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.train_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.TrainAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_train_agent_from_dict(): + test_train_agent(request_type=dict) + + +def test_train_agent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_agent), + '__call__') as call: + client.train_agent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent.TrainAgentRequest() + + +@pytest.mark.asyncio +async def test_train_agent_async(transport: str = 'grpc_asyncio', request_type=agent.TrainAgentRequest): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_agent), + '__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.train_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == agent.TrainAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_train_agent_async_from_dict(): + await test_train_agent_async(request_type=dict) + + +def test_train_agent_field_headers(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.TrainAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_agent), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.train_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_train_agent_field_headers_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.TrainAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_agent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.train_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_train_agent_flattened(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_agent), + '__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.train_agent( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_train_agent_flattened_error(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.train_agent( + agent.TrainAgentRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_train_agent_flattened_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_agent), + '__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.train_agent( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_train_agent_flattened_error_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.train_agent( + agent.TrainAgentRequest(), + parent='parent_value', + ) + + +def test_export_agent(transport: str = 'grpc', request_type=agent.ExportAgentRequest): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.export_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.ExportAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_export_agent_from_dict(): + test_export_agent(request_type=dict) + + +def test_export_agent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_agent), + '__call__') as call: + client.export_agent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent.ExportAgentRequest() + + +@pytest.mark.asyncio +async def test_export_agent_async(transport: str = 'grpc_asyncio', request_type=agent.ExportAgentRequest): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_agent), + '__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.export_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == agent.ExportAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_export_agent_async_from_dict(): + await test_export_agent_async(request_type=dict) + + +def test_export_agent_field_headers(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.ExportAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_agent), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.export_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_export_agent_field_headers_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.ExportAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_agent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.export_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_export_agent_flattened(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_agent), + '__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.export_agent( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_export_agent_flattened_error(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.export_agent( + agent.ExportAgentRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_export_agent_flattened_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_agent), + '__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.export_agent( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_export_agent_flattened_error_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.export_agent( + agent.ExportAgentRequest(), + parent='parent_value', + ) + + +def test_import_agent(transport: str = 'grpc', request_type=agent.ImportAgentRequest): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.ImportAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_agent_from_dict(): + test_import_agent(request_type=dict) + + +def test_import_agent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=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_agent), + '__call__') as call: + client.import_agent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent.ImportAgentRequest() + + +@pytest.mark.asyncio +async def test_import_agent_async(transport: str = 'grpc_asyncio', request_type=agent.ImportAgentRequest): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_agent), + '__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_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == agent.ImportAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_agent_async_from_dict(): + await test_import_agent_async(request_type=dict) + + +def test_import_agent_field_headers(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.ImportAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_agent), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_agent_field_headers_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.ImportAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_agent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_restore_agent(transport: str = 'grpc', request_type=agent.RestoreAgentRequest): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.restore_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.RestoreAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_restore_agent_from_dict(): + test_restore_agent(request_type=dict) + + +def test_restore_agent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_agent), + '__call__') as call: + client.restore_agent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent.RestoreAgentRequest() + + +@pytest.mark.asyncio +async def test_restore_agent_async(transport: str = 'grpc_asyncio', request_type=agent.RestoreAgentRequest): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_agent), + '__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.restore_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == agent.RestoreAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_restore_agent_async_from_dict(): + await test_restore_agent_async(request_type=dict) + + +def test_restore_agent_field_headers(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.RestoreAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_agent), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.restore_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_restore_agent_field_headers_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.RestoreAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_agent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.restore_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_get_validation_result(transport: str = 'grpc', request_type=agent.GetValidationResultRequest): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_validation_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = validation_result.ValidationResult( + ) + response = client.get_validation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetValidationResultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, validation_result.ValidationResult) + + +def test_get_validation_result_from_dict(): + test_get_validation_result(request_type=dict) + + +def test_get_validation_result_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=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_validation_result), + '__call__') as call: + client.get_validation_result() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetValidationResultRequest() + + +@pytest.mark.asyncio +async def test_get_validation_result_async(transport: str = 'grpc_asyncio', request_type=agent.GetValidationResultRequest): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_validation_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(validation_result.ValidationResult( + )) + response = await client.get_validation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetValidationResultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, validation_result.ValidationResult) + + +@pytest.mark.asyncio +async def test_get_validation_result_async_from_dict(): + await test_get_validation_result_async(request_type=dict) + + +def test_get_validation_result_field_headers(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.GetValidationResultRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_validation_result), + '__call__') as call: + call.return_value = validation_result.ValidationResult() + client.get_validation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_get_validation_result_field_headers_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent.GetValidationResultRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_validation_result), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(validation_result.ValidationResult()) + await client.get_validation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AgentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AgentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AgentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AgentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AgentsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AgentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AgentsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AgentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AgentsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AgentsGrpcTransport, + transports.AgentsGrpcAsyncIOTransport, +]) +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 = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AgentsGrpcTransport, + ) + +def test_agents_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AgentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_agents_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2beta1.services.agents.transports.AgentsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AgentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_agent', + 'set_agent', + 'delete_agent', + 'search_agents', + 'train_agent', + 'export_agent', + 'import_agent', + 'restore_agent', + 'get_validation_result', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +def test_agents_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.dialogflow_v2beta1.services.agents.transports.AgentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AgentsTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_agents_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.dialogflow_v2beta1.services.agents.transports.AgentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AgentsTransport() + adc.assert_called_once() + + +def test_agents_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) + AgentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AgentsGrpcTransport, + transports.AgentsGrpcAsyncIOTransport, + ], +) +def test_agents_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AgentsGrpcTransport, grpc_helpers), + (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_agents_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport]) +def test_agents_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_agents_host_no_port(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_agents_host_with_port(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_agents_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AgentsGrpcTransport( + 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_agents_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AgentsGrpcAsyncIOTransport( + 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.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport]) +def test_agents_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.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport]) +def test_agents_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_agents_grpc_lro_client(): + client = AgentsClient( + 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_agents_grpc_lro_async_client(): + client = AgentsAsyncClient( + 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_agent_path(): + project = "squid" + expected = "projects/{project}/agent".format(project=project, ) + actual = AgentsClient.agent_path(project) + assert expected == actual + + +def test_parse_agent_path(): + expected = { + "project": "clam", + } + path = AgentsClient.agent_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.parse_agent_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AgentsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = AgentsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = AgentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = AgentsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AgentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = AgentsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = AgentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = AgentsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = AgentsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = AgentsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.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.AgentsTransport, '_prep_wrapped_messages') as prep: + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AgentsTransport, '_prep_wrapped_messages') as prep: + transport_class = AgentsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = AgentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_answer_records.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_answer_records.py new file mode 100644 index 000000000..af605796d --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_answer_records.py @@ -0,0 +1,1741 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.answer_records import AnswerRecordsAsyncClient +from google.cloud.dialogflow_v2beta1.services.answer_records import AnswerRecordsClient +from google.cloud.dialogflow_v2beta1.services.answer_records import pagers +from google.cloud.dialogflow_v2beta1.services.answer_records import transports +from google.cloud.dialogflow_v2beta1.types import answer_record +from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record +from google.cloud.dialogflow_v2beta1.types import participant +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert AnswerRecordsClient._get_default_mtls_endpoint(None) is None + assert AnswerRecordsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AnswerRecordsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AnswerRecordsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AnswerRecordsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AnswerRecordsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + AnswerRecordsClient, + AnswerRecordsAsyncClient, +]) +def test_answer_records_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AnswerRecordsGrpcTransport, "grpc"), + (transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_answer_records_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + AnswerRecordsClient, + AnswerRecordsAsyncClient, +]) +def test_answer_records_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 == 'dialogflow.googleapis.com:443' + + +def test_answer_records_client_get_transport_class(): + transport = AnswerRecordsClient.get_transport_class() + available_transports = [ + transports.AnswerRecordsGrpcTransport, + ] + assert transport in available_transports + + transport = AnswerRecordsClient.get_transport_class("grpc") + assert transport == transports.AnswerRecordsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc"), + (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(AnswerRecordsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AnswerRecordsClient)) +@mock.patch.object(AnswerRecordsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AnswerRecordsAsyncClient)) +def test_answer_records_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(AnswerRecordsClient, '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(AnswerRecordsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc", "true"), + (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc", "false"), + (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(AnswerRecordsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AnswerRecordsClient)) +@mock.patch.object(AnswerRecordsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AnswerRecordsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_answer_records_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc"), + (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_answer_records_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc"), + (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_answer_records_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_answer_records_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2beta1.services.answer_records.transports.AnswerRecordsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AnswerRecordsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_get_answer_record(transport: str = 'grpc', request_type=answer_record.GetAnswerRecordRequest): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_answer_record), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = answer_record.AnswerRecord( + name='name_value', + agent_assistant_record=answer_record.AgentAssistantRecord(article_suggestion_answer=participant.ArticleAnswer(title='title_value')), + ) + response = client.get_answer_record(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == answer_record.GetAnswerRecordRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, answer_record.AnswerRecord) + assert response.name == 'name_value' + + +def test_get_answer_record_from_dict(): + test_get_answer_record(request_type=dict) + + +def test_get_answer_record_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnswerRecordsClient( + credentials=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_answer_record), + '__call__') as call: + client.get_answer_record() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == answer_record.GetAnswerRecordRequest() + + +@pytest.mark.asyncio +async def test_get_answer_record_async(transport: str = 'grpc_asyncio', request_type=answer_record.GetAnswerRecordRequest): + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_answer_record), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(answer_record.AnswerRecord( + name='name_value', + )) + response = await client.get_answer_record(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == answer_record.GetAnswerRecordRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, answer_record.AnswerRecord) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_answer_record_async_from_dict(): + await test_get_answer_record_async(request_type=dict) + + +def test_get_answer_record_field_headers(): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = answer_record.GetAnswerRecordRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_answer_record), + '__call__') as call: + call.return_value = answer_record.AnswerRecord() + client.get_answer_record(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_answer_record_field_headers_async(): + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = answer_record.GetAnswerRecordRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_answer_record), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(answer_record.AnswerRecord()) + await client.get_answer_record(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_list_answer_records(transport: str = 'grpc', request_type=answer_record.ListAnswerRecordsRequest): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_answer_records), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = answer_record.ListAnswerRecordsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_answer_records(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == answer_record.ListAnswerRecordsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAnswerRecordsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_answer_records_from_dict(): + test_list_answer_records(request_type=dict) + + +def test_list_answer_records_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnswerRecordsClient( + credentials=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_answer_records), + '__call__') as call: + client.list_answer_records() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == answer_record.ListAnswerRecordsRequest() + + +@pytest.mark.asyncio +async def test_list_answer_records_async(transport: str = 'grpc_asyncio', request_type=answer_record.ListAnswerRecordsRequest): + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_answer_records), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(answer_record.ListAnswerRecordsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_answer_records(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == answer_record.ListAnswerRecordsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAnswerRecordsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_answer_records_async_from_dict(): + await test_list_answer_records_async(request_type=dict) + + +def test_list_answer_records_field_headers(): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = answer_record.ListAnswerRecordsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_answer_records), + '__call__') as call: + call.return_value = answer_record.ListAnswerRecordsResponse() + client.list_answer_records(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_answer_records_field_headers_async(): + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = answer_record.ListAnswerRecordsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_answer_records), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(answer_record.ListAnswerRecordsResponse()) + await client.list_answer_records(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_answer_records_flattened(): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_answer_records), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = answer_record.ListAnswerRecordsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_answer_records( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_answer_records_flattened_error(): + client = AnswerRecordsClient( + credentials=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_answer_records( + answer_record.ListAnswerRecordsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_answer_records_flattened_async(): + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_answer_records), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = answer_record.ListAnswerRecordsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(answer_record.ListAnswerRecordsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_answer_records( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_answer_records_flattened_error_async(): + client = AnswerRecordsAsyncClient( + credentials=ga_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_answer_records( + answer_record.ListAnswerRecordsRequest(), + parent='parent_value', + ) + + +def test_list_answer_records_pager(): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_answer_records), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + answer_record.ListAnswerRecordsResponse( + answer_records=[ + answer_record.AnswerRecord(), + answer_record.AnswerRecord(), + answer_record.AnswerRecord(), + ], + next_page_token='abc', + ), + answer_record.ListAnswerRecordsResponse( + answer_records=[], + next_page_token='def', + ), + answer_record.ListAnswerRecordsResponse( + answer_records=[ + answer_record.AnswerRecord(), + ], + next_page_token='ghi', + ), + answer_record.ListAnswerRecordsResponse( + answer_records=[ + answer_record.AnswerRecord(), + answer_record.AnswerRecord(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_answer_records(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, answer_record.AnswerRecord) + for i in results) + +def test_list_answer_records_pages(): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_answer_records), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + answer_record.ListAnswerRecordsResponse( + answer_records=[ + answer_record.AnswerRecord(), + answer_record.AnswerRecord(), + answer_record.AnswerRecord(), + ], + next_page_token='abc', + ), + answer_record.ListAnswerRecordsResponse( + answer_records=[], + next_page_token='def', + ), + answer_record.ListAnswerRecordsResponse( + answer_records=[ + answer_record.AnswerRecord(), + ], + next_page_token='ghi', + ), + answer_record.ListAnswerRecordsResponse( + answer_records=[ + answer_record.AnswerRecord(), + answer_record.AnswerRecord(), + ], + ), + RuntimeError, + ) + pages = list(client.list_answer_records(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_answer_records_async_pager(): + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_answer_records), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + answer_record.ListAnswerRecordsResponse( + answer_records=[ + answer_record.AnswerRecord(), + answer_record.AnswerRecord(), + answer_record.AnswerRecord(), + ], + next_page_token='abc', + ), + answer_record.ListAnswerRecordsResponse( + answer_records=[], + next_page_token='def', + ), + answer_record.ListAnswerRecordsResponse( + answer_records=[ + answer_record.AnswerRecord(), + ], + next_page_token='ghi', + ), + answer_record.ListAnswerRecordsResponse( + answer_records=[ + answer_record.AnswerRecord(), + answer_record.AnswerRecord(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_answer_records(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, answer_record.AnswerRecord) + for i in responses) + +@pytest.mark.asyncio +async def test_list_answer_records_async_pages(): + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_answer_records), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + answer_record.ListAnswerRecordsResponse( + answer_records=[ + answer_record.AnswerRecord(), + answer_record.AnswerRecord(), + answer_record.AnswerRecord(), + ], + next_page_token='abc', + ), + answer_record.ListAnswerRecordsResponse( + answer_records=[], + next_page_token='def', + ), + answer_record.ListAnswerRecordsResponse( + answer_records=[ + answer_record.AnswerRecord(), + ], + next_page_token='ghi', + ), + answer_record.ListAnswerRecordsResponse( + answer_records=[ + answer_record.AnswerRecord(), + answer_record.AnswerRecord(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_answer_records(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_answer_record(transport: str = 'grpc', request_type=gcd_answer_record.UpdateAnswerRecordRequest): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_answer_record), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_answer_record.AnswerRecord( + name='name_value', + agent_assistant_record=gcd_answer_record.AgentAssistantRecord(article_suggestion_answer=participant.ArticleAnswer(title='title_value')), + ) + response = client.update_answer_record(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_answer_record.UpdateAnswerRecordRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_answer_record.AnswerRecord) + assert response.name == 'name_value' + + +def test_update_answer_record_from_dict(): + test_update_answer_record(request_type=dict) + + +def test_update_answer_record_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnswerRecordsClient( + credentials=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_answer_record), + '__call__') as call: + client.update_answer_record() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_answer_record.UpdateAnswerRecordRequest() + + +@pytest.mark.asyncio +async def test_update_answer_record_async(transport: str = 'grpc_asyncio', request_type=gcd_answer_record.UpdateAnswerRecordRequest): + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_answer_record), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_answer_record.AnswerRecord( + name='name_value', + )) + response = await client.update_answer_record(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_answer_record.UpdateAnswerRecordRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_answer_record.AnswerRecord) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_update_answer_record_async_from_dict(): + await test_update_answer_record_async(request_type=dict) + + +def test_update_answer_record_field_headers(): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_answer_record.UpdateAnswerRecordRequest() + + request.answer_record.name = 'answer_record.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_answer_record), + '__call__') as call: + call.return_value = gcd_answer_record.AnswerRecord() + client.update_answer_record(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'answer_record.name=answer_record.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_answer_record_field_headers_async(): + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_answer_record.UpdateAnswerRecordRequest() + + request.answer_record.name = 'answer_record.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_answer_record), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_answer_record.AnswerRecord()) + await client.update_answer_record(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'answer_record.name=answer_record.name/value', + ) in kw['metadata'] + + +def test_update_answer_record_flattened(): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_answer_record), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_answer_record.AnswerRecord() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_answer_record( + answer_record=gcd_answer_record.AnswerRecord(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].answer_record + mock_val = gcd_answer_record.AnswerRecord(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_answer_record_flattened_error(): + client = AnswerRecordsClient( + credentials=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_answer_record( + gcd_answer_record.UpdateAnswerRecordRequest(), + answer_record=gcd_answer_record.AnswerRecord(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_answer_record_flattened_async(): + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_answer_record), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_answer_record.AnswerRecord() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_answer_record.AnswerRecord()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_answer_record( + answer_record=gcd_answer_record.AnswerRecord(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].answer_record + mock_val = gcd_answer_record.AnswerRecord(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_answer_record_flattened_error_async(): + client = AnswerRecordsAsyncClient( + credentials=ga_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_answer_record( + gcd_answer_record.UpdateAnswerRecordRequest(), + answer_record=gcd_answer_record.AnswerRecord(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AnswerRecordsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AnswerRecordsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AnswerRecordsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AnswerRecordsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AnswerRecordsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AnswerRecordsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AnswerRecordsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AnswerRecordsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AnswerRecordsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AnswerRecordsGrpcTransport, + transports.AnswerRecordsGrpcAsyncIOTransport, +]) +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 = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AnswerRecordsGrpcTransport, + ) + +def test_answer_records_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AnswerRecordsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_answer_records_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2beta1.services.answer_records.transports.AnswerRecordsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AnswerRecordsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_answer_record', + 'list_answer_records', + 'update_answer_record', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_answer_records_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.dialogflow_v2beta1.services.answer_records.transports.AnswerRecordsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AnswerRecordsTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_answer_records_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.dialogflow_v2beta1.services.answer_records.transports.AnswerRecordsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AnswerRecordsTransport() + adc.assert_called_once() + + +def test_answer_records_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) + AnswerRecordsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AnswerRecordsGrpcTransport, + transports.AnswerRecordsGrpcAsyncIOTransport, + ], +) +def test_answer_records_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AnswerRecordsGrpcTransport, grpc_helpers), + (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_answer_records_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AnswerRecordsGrpcTransport, transports.AnswerRecordsGrpcAsyncIOTransport]) +def test_answer_records_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_answer_records_host_no_port(): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_answer_records_host_with_port(): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_answer_records_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AnswerRecordsGrpcTransport( + 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_answer_records_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AnswerRecordsGrpcAsyncIOTransport( + 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.AnswerRecordsGrpcTransport, transports.AnswerRecordsGrpcAsyncIOTransport]) +def test_answer_records_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.AnswerRecordsGrpcTransport, transports.AnswerRecordsGrpcAsyncIOTransport]) +def test_answer_records_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_answer_record_path(): + project = "squid" + answer_record = "clam" + expected = "projects/{project}/answerRecords/{answer_record}".format(project=project, answer_record=answer_record, ) + actual = AnswerRecordsClient.answer_record_path(project, answer_record) + assert expected == actual + + +def test_parse_answer_record_path(): + expected = { + "project": "whelk", + "answer_record": "octopus", + } + path = AnswerRecordsClient.answer_record_path(**expected) + + # Check that the path construction is reversible. + actual = AnswerRecordsClient.parse_answer_record_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AnswerRecordsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = AnswerRecordsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AnswerRecordsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = AnswerRecordsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = AnswerRecordsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AnswerRecordsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AnswerRecordsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = AnswerRecordsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AnswerRecordsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = AnswerRecordsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = AnswerRecordsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AnswerRecordsClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = AnswerRecordsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = AnswerRecordsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AnswerRecordsClient.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.AnswerRecordsTransport, '_prep_wrapped_messages') as prep: + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AnswerRecordsTransport, '_prep_wrapped_messages') as prep: + transport_class = AnswerRecordsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = AnswerRecordsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_contexts.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_contexts.py new file mode 100644 index 000000000..5b6e3c3a8 --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_contexts.py @@ -0,0 +1,2542 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.contexts import ContextsAsyncClient +from google.cloud.dialogflow_v2beta1.services.contexts import ContextsClient +from google.cloud.dialogflow_v2beta1.services.contexts import pagers +from google.cloud.dialogflow_v2beta1.services.contexts import transports +from google.cloud.dialogflow_v2beta1.types import context +from google.cloud.dialogflow_v2beta1.types import context as gcd_context +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ContextsClient._get_default_mtls_endpoint(None) is None + assert ContextsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ContextsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ContextsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ContextsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ContextsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + ContextsClient, + ContextsAsyncClient, +]) +def test_contexts_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ContextsGrpcTransport, "grpc"), + (transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_contexts_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + ContextsClient, + ContextsAsyncClient, +]) +def test_contexts_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 == 'dialogflow.googleapis.com:443' + + +def test_contexts_client_get_transport_class(): + transport = ContextsClient.get_transport_class() + available_transports = [ + transports.ContextsGrpcTransport, + ] + assert transport in available_transports + + transport = ContextsClient.get_transport_class("grpc") + assert transport == transports.ContextsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ContextsClient, transports.ContextsGrpcTransport, "grpc"), + (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ContextsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ContextsClient)) +@mock.patch.object(ContextsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ContextsAsyncClient)) +def test_contexts_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(ContextsClient, '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(ContextsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ContextsClient, transports.ContextsGrpcTransport, "grpc", "true"), + (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ContextsClient, transports.ContextsGrpcTransport, "grpc", "false"), + (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ContextsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ContextsClient)) +@mock.patch.object(ContextsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ContextsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_contexts_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ContextsClient, transports.ContextsGrpcTransport, "grpc"), + (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_contexts_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ContextsClient, transports.ContextsGrpcTransport, "grpc"), + (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_contexts_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_contexts_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2beta1.services.contexts.transports.ContextsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ContextsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_contexts(transport: str = 'grpc', request_type=context.ListContextsRequest): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_contexts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = context.ListContextsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_contexts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == context.ListContextsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListContextsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_contexts_from_dict(): + test_list_contexts(request_type=dict) + + +def test_list_contexts_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ContextsClient( + credentials=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_contexts), + '__call__') as call: + client.list_contexts() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == context.ListContextsRequest() + + +@pytest.mark.asyncio +async def test_list_contexts_async(transport: str = 'grpc_asyncio', request_type=context.ListContextsRequest): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_contexts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(context.ListContextsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_contexts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == context.ListContextsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListContextsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_contexts_async_from_dict(): + await test_list_contexts_async(request_type=dict) + + +def test_list_contexts_field_headers(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = context.ListContextsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_contexts), + '__call__') as call: + call.return_value = context.ListContextsResponse() + client.list_contexts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_contexts_field_headers_async(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = context.ListContextsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_contexts), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(context.ListContextsResponse()) + await client.list_contexts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_contexts_flattened(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_contexts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = context.ListContextsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_contexts( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_contexts_flattened_error(): + client = ContextsClient( + credentials=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_contexts( + context.ListContextsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_contexts_flattened_async(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_contexts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = context.ListContextsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(context.ListContextsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_contexts( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_contexts_flattened_error_async(): + client = ContextsAsyncClient( + credentials=ga_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_contexts( + context.ListContextsRequest(), + parent='parent_value', + ) + + +def test_list_contexts_pager(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_contexts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + context.ListContextsResponse( + contexts=[ + context.Context(), + context.Context(), + context.Context(), + ], + next_page_token='abc', + ), + context.ListContextsResponse( + contexts=[], + next_page_token='def', + ), + context.ListContextsResponse( + contexts=[ + context.Context(), + ], + next_page_token='ghi', + ), + context.ListContextsResponse( + contexts=[ + context.Context(), + context.Context(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_contexts(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, context.Context) + for i in results) + +def test_list_contexts_pages(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_contexts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + context.ListContextsResponse( + contexts=[ + context.Context(), + context.Context(), + context.Context(), + ], + next_page_token='abc', + ), + context.ListContextsResponse( + contexts=[], + next_page_token='def', + ), + context.ListContextsResponse( + contexts=[ + context.Context(), + ], + next_page_token='ghi', + ), + context.ListContextsResponse( + contexts=[ + context.Context(), + context.Context(), + ], + ), + RuntimeError, + ) + pages = list(client.list_contexts(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_contexts_async_pager(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_contexts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + context.ListContextsResponse( + contexts=[ + context.Context(), + context.Context(), + context.Context(), + ], + next_page_token='abc', + ), + context.ListContextsResponse( + contexts=[], + next_page_token='def', + ), + context.ListContextsResponse( + contexts=[ + context.Context(), + ], + next_page_token='ghi', + ), + context.ListContextsResponse( + contexts=[ + context.Context(), + context.Context(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_contexts(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, context.Context) + for i in responses) + +@pytest.mark.asyncio +async def test_list_contexts_async_pages(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_contexts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + context.ListContextsResponse( + contexts=[ + context.Context(), + context.Context(), + context.Context(), + ], + next_page_token='abc', + ), + context.ListContextsResponse( + contexts=[], + next_page_token='def', + ), + context.ListContextsResponse( + contexts=[ + context.Context(), + ], + next_page_token='ghi', + ), + context.ListContextsResponse( + contexts=[ + context.Context(), + context.Context(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_contexts(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_context(transport: str = 'grpc', request_type=context.GetContextRequest): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = context.Context( + name='name_value', + lifespan_count=1498, + ) + response = client.get_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == context.GetContextRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, context.Context) + assert response.name == 'name_value' + assert response.lifespan_count == 1498 + + +def test_get_context_from_dict(): + test_get_context(request_type=dict) + + +def test_get_context_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ContextsClient( + credentials=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_context), + '__call__') as call: + client.get_context() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == context.GetContextRequest() + + +@pytest.mark.asyncio +async def test_get_context_async(transport: str = 'grpc_asyncio', request_type=context.GetContextRequest): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(context.Context( + name='name_value', + lifespan_count=1498, + )) + response = await client.get_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == context.GetContextRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, context.Context) + assert response.name == 'name_value' + assert response.lifespan_count == 1498 + + +@pytest.mark.asyncio +async def test_get_context_async_from_dict(): + await test_get_context_async(request_type=dict) + + +def test_get_context_field_headers(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = context.GetContextRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_context), + '__call__') as call: + call.return_value = context.Context() + client.get_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_context_field_headers_async(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = context.GetContextRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_context), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(context.Context()) + await client.get_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_context_flattened(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = context.Context() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_context( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_context_flattened_error(): + client = ContextsClient( + credentials=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_context( + context.GetContextRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_context_flattened_async(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = context.Context() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(context.Context()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_context( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_context_flattened_error_async(): + client = ContextsAsyncClient( + credentials=ga_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_context( + context.GetContextRequest(), + name='name_value', + ) + + +def test_create_context(transport: str = 'grpc', request_type=gcd_context.CreateContextRequest): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_context.Context( + name='name_value', + lifespan_count=1498, + ) + response = client.create_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_context.CreateContextRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_context.Context) + assert response.name == 'name_value' + assert response.lifespan_count == 1498 + + +def test_create_context_from_dict(): + test_create_context(request_type=dict) + + +def test_create_context_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ContextsClient( + credentials=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_context), + '__call__') as call: + client.create_context() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_context.CreateContextRequest() + + +@pytest.mark.asyncio +async def test_create_context_async(transport: str = 'grpc_asyncio', request_type=gcd_context.CreateContextRequest): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context( + name='name_value', + lifespan_count=1498, + )) + response = await client.create_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_context.CreateContextRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_context.Context) + assert response.name == 'name_value' + assert response.lifespan_count == 1498 + + +@pytest.mark.asyncio +async def test_create_context_async_from_dict(): + await test_create_context_async(request_type=dict) + + +def test_create_context_field_headers(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_context.CreateContextRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_context), + '__call__') as call: + call.return_value = gcd_context.Context() + client.create_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_context_field_headers_async(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_context.CreateContextRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_context), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context()) + await client.create_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_context_flattened(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_context.Context() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_context( + parent='parent_value', + context=gcd_context.Context(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].context + mock_val = gcd_context.Context(name='name_value') + assert arg == mock_val + + +def test_create_context_flattened_error(): + client = ContextsClient( + credentials=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_context( + gcd_context.CreateContextRequest(), + parent='parent_value', + context=gcd_context.Context(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_context_flattened_async(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_context.Context() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_context( + parent='parent_value', + context=gcd_context.Context(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].context + mock_val = gcd_context.Context(name='name_value') + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_context_flattened_error_async(): + client = ContextsAsyncClient( + credentials=ga_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_context( + gcd_context.CreateContextRequest(), + parent='parent_value', + context=gcd_context.Context(name='name_value'), + ) + + +def test_update_context(transport: str = 'grpc', request_type=gcd_context.UpdateContextRequest): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_context.Context( + name='name_value', + lifespan_count=1498, + ) + response = client.update_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_context.UpdateContextRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_context.Context) + assert response.name == 'name_value' + assert response.lifespan_count == 1498 + + +def test_update_context_from_dict(): + test_update_context(request_type=dict) + + +def test_update_context_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ContextsClient( + credentials=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_context), + '__call__') as call: + client.update_context() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_context.UpdateContextRequest() + + +@pytest.mark.asyncio +async def test_update_context_async(transport: str = 'grpc_asyncio', request_type=gcd_context.UpdateContextRequest): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context( + name='name_value', + lifespan_count=1498, + )) + response = await client.update_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_context.UpdateContextRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_context.Context) + assert response.name == 'name_value' + assert response.lifespan_count == 1498 + + +@pytest.mark.asyncio +async def test_update_context_async_from_dict(): + await test_update_context_async(request_type=dict) + + +def test_update_context_field_headers(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_context.UpdateContextRequest() + + request.context.name = 'context.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_context), + '__call__') as call: + call.return_value = gcd_context.Context() + client.update_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'context.name=context.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_context_field_headers_async(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_context.UpdateContextRequest() + + request.context.name = 'context.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_context), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context()) + await client.update_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'context.name=context.name/value', + ) in kw['metadata'] + + +def test_update_context_flattened(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_context.Context() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_context( + context=gcd_context.Context(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].context + mock_val = gcd_context.Context(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_context_flattened_error(): + client = ContextsClient( + credentials=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_context( + gcd_context.UpdateContextRequest(), + context=gcd_context.Context(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_context_flattened_async(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_context.Context() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_context( + context=gcd_context.Context(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].context + mock_val = gcd_context.Context(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_context_flattened_error_async(): + client = ContextsAsyncClient( + credentials=ga_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_context( + gcd_context.UpdateContextRequest(), + context=gcd_context.Context(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_context(transport: str = 'grpc', request_type=context.DeleteContextRequest): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == context.DeleteContextRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_context_from_dict(): + test_delete_context(request_type=dict) + + +def test_delete_context_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ContextsClient( + credentials=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_context), + '__call__') as call: + client.delete_context() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == context.DeleteContextRequest() + + +@pytest.mark.asyncio +async def test_delete_context_async(transport: str = 'grpc_asyncio', request_type=context.DeleteContextRequest): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_context), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == context.DeleteContextRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_context_async_from_dict(): + await test_delete_context_async(request_type=dict) + + +def test_delete_context_field_headers(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = context.DeleteContextRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_context), + '__call__') as call: + call.return_value = None + client.delete_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_context_field_headers_async(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = context.DeleteContextRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_context), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_context(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_context_flattened(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_context), + '__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_context( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_context_flattened_error(): + client = ContextsClient( + credentials=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_context( + context.DeleteContextRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_context_flattened_async(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_context), + '__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_context( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_context_flattened_error_async(): + client = ContextsAsyncClient( + credentials=ga_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_context( + context.DeleteContextRequest(), + name='name_value', + ) + + +def test_delete_all_contexts(transport: str = 'grpc', request_type=context.DeleteAllContextsRequest): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_all_contexts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_all_contexts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == context.DeleteAllContextsRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_all_contexts_from_dict(): + test_delete_all_contexts(request_type=dict) + + +def test_delete_all_contexts_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ContextsClient( + credentials=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_all_contexts), + '__call__') as call: + client.delete_all_contexts() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == context.DeleteAllContextsRequest() + + +@pytest.mark.asyncio +async def test_delete_all_contexts_async(transport: str = 'grpc_asyncio', request_type=context.DeleteAllContextsRequest): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_all_contexts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_all_contexts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == context.DeleteAllContextsRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_all_contexts_async_from_dict(): + await test_delete_all_contexts_async(request_type=dict) + + +def test_delete_all_contexts_field_headers(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = context.DeleteAllContextsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_all_contexts), + '__call__') as call: + call.return_value = None + client.delete_all_contexts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_delete_all_contexts_field_headers_async(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = context.DeleteAllContextsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_all_contexts), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_all_contexts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_delete_all_contexts_flattened(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_all_contexts), + '__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_all_contexts( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_delete_all_contexts_flattened_error(): + client = ContextsClient( + credentials=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_all_contexts( + context.DeleteAllContextsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_delete_all_contexts_flattened_async(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_all_contexts), + '__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_all_contexts( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_all_contexts_flattened_error_async(): + client = ContextsAsyncClient( + credentials=ga_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_all_contexts( + context.DeleteAllContextsRequest(), + parent='parent_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ContextsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ContextsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ContextsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ContextsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ContextsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ContextsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ContextsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ContextsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ContextsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ContextsGrpcTransport, + transports.ContextsGrpcAsyncIOTransport, +]) +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 = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ContextsGrpcTransport, + ) + +def test_contexts_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ContextsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_contexts_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2beta1.services.contexts.transports.ContextsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ContextsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_contexts', + 'get_context', + 'create_context', + 'update_context', + 'delete_context', + 'delete_all_contexts', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_contexts_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.dialogflow_v2beta1.services.contexts.transports.ContextsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ContextsTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_contexts_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.dialogflow_v2beta1.services.contexts.transports.ContextsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ContextsTransport() + adc.assert_called_once() + + +def test_contexts_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) + ContextsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ContextsGrpcTransport, + transports.ContextsGrpcAsyncIOTransport, + ], +) +def test_contexts_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ContextsGrpcTransport, grpc_helpers), + (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_contexts_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ContextsGrpcTransport, transports.ContextsGrpcAsyncIOTransport]) +def test_contexts_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_contexts_host_no_port(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_contexts_host_with_port(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_contexts_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ContextsGrpcTransport( + 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_contexts_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ContextsGrpcAsyncIOTransport( + 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.ContextsGrpcTransport, transports.ContextsGrpcAsyncIOTransport]) +def test_contexts_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.ContextsGrpcTransport, transports.ContextsGrpcAsyncIOTransport]) +def test_contexts_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_context_path(): + project = "squid" + session = "clam" + context = "whelk" + expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) + actual = ContextsClient.context_path(project, session, context) + assert expected == actual + + +def test_parse_context_path(): + expected = { + "project": "octopus", + "session": "oyster", + "context": "nudibranch", + } + path = ContextsClient.context_path(**expected) + + # Check that the path construction is reversible. + actual = ContextsClient.parse_context_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ContextsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = ContextsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ContextsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = ContextsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = ContextsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ContextsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ContextsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = ContextsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ContextsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = ContextsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = ContextsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ContextsClient.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 = ContextsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = ContextsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ContextsClient.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.ContextsTransport, '_prep_wrapped_messages') as prep: + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ContextsTransport, '_prep_wrapped_messages') as prep: + transport_class = ContextsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = ContextsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = ContextsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_conversation_profiles.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_conversation_profiles.py new file mode 100644 index 000000000..4a7041d95 --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_conversation_profiles.py @@ -0,0 +1,2447 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.conversation_profiles import ConversationProfilesAsyncClient +from google.cloud.dialogflow_v2beta1.services.conversation_profiles import ConversationProfilesClient +from google.cloud.dialogflow_v2beta1.services.conversation_profiles import pagers +from google.cloud.dialogflow_v2beta1.services.conversation_profiles import transports +from google.cloud.dialogflow_v2beta1.types import audio_config +from google.cloud.dialogflow_v2beta1.types import conversation_profile +from google.cloud.dialogflow_v2beta1.types import conversation_profile as gcd_conversation_profile +from google.cloud.dialogflow_v2beta1.types import participant +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ConversationProfilesClient._get_default_mtls_endpoint(None) is None + assert ConversationProfilesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ConversationProfilesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ConversationProfilesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ConversationProfilesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ConversationProfilesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + ConversationProfilesClient, + ConversationProfilesAsyncClient, +]) +def test_conversation_profiles_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ConversationProfilesGrpcTransport, "grpc"), + (transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_conversation_profiles_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + ConversationProfilesClient, + ConversationProfilesAsyncClient, +]) +def test_conversation_profiles_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 == 'dialogflow.googleapis.com:443' + + +def test_conversation_profiles_client_get_transport_class(): + transport = ConversationProfilesClient.get_transport_class() + available_transports = [ + transports.ConversationProfilesGrpcTransport, + ] + assert transport in available_transports + + transport = ConversationProfilesClient.get_transport_class("grpc") + assert transport == transports.ConversationProfilesGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc"), + (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ConversationProfilesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationProfilesClient)) +@mock.patch.object(ConversationProfilesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationProfilesAsyncClient)) +def test_conversation_profiles_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(ConversationProfilesClient, '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(ConversationProfilesClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc", "true"), + (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc", "false"), + (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ConversationProfilesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationProfilesClient)) +@mock.patch.object(ConversationProfilesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationProfilesAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_conversation_profiles_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc"), + (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_conversation_profiles_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc"), + (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_conversation_profiles_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_conversation_profiles_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2beta1.services.conversation_profiles.transports.ConversationProfilesGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ConversationProfilesClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_conversation_profiles(transport: str = 'grpc', request_type=conversation_profile.ListConversationProfilesRequest): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation_profiles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation_profile.ListConversationProfilesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_conversation_profiles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == conversation_profile.ListConversationProfilesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversationProfilesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_conversation_profiles_from_dict(): + test_list_conversation_profiles(request_type=dict) + + +def test_list_conversation_profiles_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationProfilesClient( + credentials=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_conversation_profiles), + '__call__') as call: + client.list_conversation_profiles() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversation_profile.ListConversationProfilesRequest() + + +@pytest.mark.asyncio +async def test_list_conversation_profiles_async(transport: str = 'grpc_asyncio', request_type=conversation_profile.ListConversationProfilesRequest): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation_profiles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation_profile.ListConversationProfilesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_conversation_profiles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversation_profile.ListConversationProfilesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversationProfilesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_conversation_profiles_async_from_dict(): + await test_list_conversation_profiles_async(request_type=dict) + + +def test_list_conversation_profiles_field_headers(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation_profile.ListConversationProfilesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversation_profiles), + '__call__') as call: + call.return_value = conversation_profile.ListConversationProfilesResponse() + client.list_conversation_profiles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_conversation_profiles_field_headers_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation_profile.ListConversationProfilesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversation_profiles), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation_profile.ListConversationProfilesResponse()) + await client.list_conversation_profiles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_conversation_profiles_flattened(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversation_profiles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation_profile.ListConversationProfilesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_conversation_profiles( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_conversation_profiles_flattened_error(): + client = ConversationProfilesClient( + credentials=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_conversation_profiles( + conversation_profile.ListConversationProfilesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_conversation_profiles_flattened_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversation_profiles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation_profile.ListConversationProfilesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation_profile.ListConversationProfilesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_conversation_profiles( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_conversation_profiles_flattened_error_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_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_conversation_profiles( + conversation_profile.ListConversationProfilesRequest(), + parent='parent_value', + ) + + +def test_list_conversation_profiles_pager(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversation_profiles), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[ + conversation_profile.ConversationProfile(), + conversation_profile.ConversationProfile(), + conversation_profile.ConversationProfile(), + ], + next_page_token='abc', + ), + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[], + next_page_token='def', + ), + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[ + conversation_profile.ConversationProfile(), + ], + next_page_token='ghi', + ), + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[ + conversation_profile.ConversationProfile(), + conversation_profile.ConversationProfile(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_conversation_profiles(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, conversation_profile.ConversationProfile) + for i in results) + +def test_list_conversation_profiles_pages(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversation_profiles), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[ + conversation_profile.ConversationProfile(), + conversation_profile.ConversationProfile(), + conversation_profile.ConversationProfile(), + ], + next_page_token='abc', + ), + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[], + next_page_token='def', + ), + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[ + conversation_profile.ConversationProfile(), + ], + next_page_token='ghi', + ), + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[ + conversation_profile.ConversationProfile(), + conversation_profile.ConversationProfile(), + ], + ), + RuntimeError, + ) + pages = list(client.list_conversation_profiles(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_conversation_profiles_async_pager(): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversation_profiles), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[ + conversation_profile.ConversationProfile(), + conversation_profile.ConversationProfile(), + conversation_profile.ConversationProfile(), + ], + next_page_token='abc', + ), + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[], + next_page_token='def', + ), + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[ + conversation_profile.ConversationProfile(), + ], + next_page_token='ghi', + ), + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[ + conversation_profile.ConversationProfile(), + conversation_profile.ConversationProfile(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_conversation_profiles(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, conversation_profile.ConversationProfile) + for i in responses) + +@pytest.mark.asyncio +async def test_list_conversation_profiles_async_pages(): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversation_profiles), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[ + conversation_profile.ConversationProfile(), + conversation_profile.ConversationProfile(), + conversation_profile.ConversationProfile(), + ], + next_page_token='abc', + ), + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[], + next_page_token='def', + ), + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[ + conversation_profile.ConversationProfile(), + ], + next_page_token='ghi', + ), + conversation_profile.ListConversationProfilesResponse( + conversation_profiles=[ + conversation_profile.ConversationProfile(), + conversation_profile.ConversationProfile(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_conversation_profiles(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_conversation_profile(transport: str = 'grpc', request_type=conversation_profile.GetConversationProfileRequest): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation_profile.ConversationProfile( + name='name_value', + display_name='display_name_value', + language_code='language_code_value', + time_zone='time_zone_value', + security_settings='security_settings_value', + ) + response = client.get_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == conversation_profile.GetConversationProfileRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, conversation_profile.ConversationProfile) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.language_code == 'language_code_value' + assert response.time_zone == 'time_zone_value' + assert response.security_settings == 'security_settings_value' + + +def test_get_conversation_profile_from_dict(): + test_get_conversation_profile(request_type=dict) + + +def test_get_conversation_profile_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationProfilesClient( + credentials=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_conversation_profile), + '__call__') as call: + client.get_conversation_profile() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversation_profile.GetConversationProfileRequest() + + +@pytest.mark.asyncio +async def test_get_conversation_profile_async(transport: str = 'grpc_asyncio', request_type=conversation_profile.GetConversationProfileRequest): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation_profile.ConversationProfile( + name='name_value', + display_name='display_name_value', + language_code='language_code_value', + time_zone='time_zone_value', + security_settings='security_settings_value', + )) + response = await client.get_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversation_profile.GetConversationProfileRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, conversation_profile.ConversationProfile) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.language_code == 'language_code_value' + assert response.time_zone == 'time_zone_value' + assert response.security_settings == 'security_settings_value' + + +@pytest.mark.asyncio +async def test_get_conversation_profile_async_from_dict(): + await test_get_conversation_profile_async(request_type=dict) + + +def test_get_conversation_profile_field_headers(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation_profile.GetConversationProfileRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation_profile), + '__call__') as call: + call.return_value = conversation_profile.ConversationProfile() + client.get_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_conversation_profile_field_headers_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation_profile.GetConversationProfileRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation_profile), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation_profile.ConversationProfile()) + await client.get_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_conversation_profile_flattened(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation_profile.ConversationProfile() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_conversation_profile( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_conversation_profile_flattened_error(): + client = ConversationProfilesClient( + credentials=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_conversation_profile( + conversation_profile.GetConversationProfileRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_conversation_profile_flattened_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation_profile.ConversationProfile() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation_profile.ConversationProfile()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_conversation_profile( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_conversation_profile_flattened_error_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_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_conversation_profile( + conversation_profile.GetConversationProfileRequest(), + name='name_value', + ) + + +def test_create_conversation_profile(transport: str = 'grpc', request_type=gcd_conversation_profile.CreateConversationProfileRequest): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation_profile.ConversationProfile( + name='name_value', + display_name='display_name_value', + language_code='language_code_value', + time_zone='time_zone_value', + security_settings='security_settings_value', + ) + response = client.create_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_conversation_profile.CreateConversationProfileRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation_profile.ConversationProfile) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.language_code == 'language_code_value' + assert response.time_zone == 'time_zone_value' + assert response.security_settings == 'security_settings_value' + + +def test_create_conversation_profile_from_dict(): + test_create_conversation_profile(request_type=dict) + + +def test_create_conversation_profile_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationProfilesClient( + credentials=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_conversation_profile), + '__call__') as call: + client.create_conversation_profile() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_conversation_profile.CreateConversationProfileRequest() + + +@pytest.mark.asyncio +async def test_create_conversation_profile_async(transport: str = 'grpc_asyncio', request_type=gcd_conversation_profile.CreateConversationProfileRequest): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation_profile.ConversationProfile( + name='name_value', + display_name='display_name_value', + language_code='language_code_value', + time_zone='time_zone_value', + security_settings='security_settings_value', + )) + response = await client.create_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_conversation_profile.CreateConversationProfileRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation_profile.ConversationProfile) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.language_code == 'language_code_value' + assert response.time_zone == 'time_zone_value' + assert response.security_settings == 'security_settings_value' + + +@pytest.mark.asyncio +async def test_create_conversation_profile_async_from_dict(): + await test_create_conversation_profile_async(request_type=dict) + + +def test_create_conversation_profile_field_headers(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_conversation_profile.CreateConversationProfileRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation_profile), + '__call__') as call: + call.return_value = gcd_conversation_profile.ConversationProfile() + client.create_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_conversation_profile_field_headers_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_conversation_profile.CreateConversationProfileRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation_profile), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation_profile.ConversationProfile()) + await client.create_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_conversation_profile_flattened(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation_profile.ConversationProfile() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_conversation_profile( + parent='parent_value', + conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].conversation_profile + mock_val = gcd_conversation_profile.ConversationProfile(name='name_value') + assert arg == mock_val + + +def test_create_conversation_profile_flattened_error(): + client = ConversationProfilesClient( + credentials=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_conversation_profile( + gcd_conversation_profile.CreateConversationProfileRequest(), + parent='parent_value', + conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_conversation_profile_flattened_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation_profile.ConversationProfile() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation_profile.ConversationProfile()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_conversation_profile( + parent='parent_value', + conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].conversation_profile + mock_val = gcd_conversation_profile.ConversationProfile(name='name_value') + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_conversation_profile_flattened_error_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_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_conversation_profile( + gcd_conversation_profile.CreateConversationProfileRequest(), + parent='parent_value', + conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), + ) + + +def test_update_conversation_profile(transport: str = 'grpc', request_type=gcd_conversation_profile.UpdateConversationProfileRequest): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation_profile.ConversationProfile( + name='name_value', + display_name='display_name_value', + language_code='language_code_value', + time_zone='time_zone_value', + security_settings='security_settings_value', + ) + response = client.update_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_conversation_profile.UpdateConversationProfileRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation_profile.ConversationProfile) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.language_code == 'language_code_value' + assert response.time_zone == 'time_zone_value' + assert response.security_settings == 'security_settings_value' + + +def test_update_conversation_profile_from_dict(): + test_update_conversation_profile(request_type=dict) + + +def test_update_conversation_profile_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationProfilesClient( + credentials=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_conversation_profile), + '__call__') as call: + client.update_conversation_profile() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_conversation_profile.UpdateConversationProfileRequest() + + +@pytest.mark.asyncio +async def test_update_conversation_profile_async(transport: str = 'grpc_asyncio', request_type=gcd_conversation_profile.UpdateConversationProfileRequest): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation_profile.ConversationProfile( + name='name_value', + display_name='display_name_value', + language_code='language_code_value', + time_zone='time_zone_value', + security_settings='security_settings_value', + )) + response = await client.update_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_conversation_profile.UpdateConversationProfileRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation_profile.ConversationProfile) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.language_code == 'language_code_value' + assert response.time_zone == 'time_zone_value' + assert response.security_settings == 'security_settings_value' + + +@pytest.mark.asyncio +async def test_update_conversation_profile_async_from_dict(): + await test_update_conversation_profile_async(request_type=dict) + + +def test_update_conversation_profile_field_headers(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_conversation_profile.UpdateConversationProfileRequest() + + request.conversation_profile.name = 'conversation_profile.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation_profile), + '__call__') as call: + call.return_value = gcd_conversation_profile.ConversationProfile() + client.update_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'conversation_profile.name=conversation_profile.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_conversation_profile_field_headers_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_conversation_profile.UpdateConversationProfileRequest() + + request.conversation_profile.name = 'conversation_profile.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation_profile), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation_profile.ConversationProfile()) + await client.update_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'conversation_profile.name=conversation_profile.name/value', + ) in kw['metadata'] + + +def test_update_conversation_profile_flattened(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation_profile.ConversationProfile() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_conversation_profile( + conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].conversation_profile + mock_val = gcd_conversation_profile.ConversationProfile(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_conversation_profile_flattened_error(): + client = ConversationProfilesClient( + credentials=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_conversation_profile( + gcd_conversation_profile.UpdateConversationProfileRequest(), + conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_conversation_profile_flattened_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation_profile.ConversationProfile() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation_profile.ConversationProfile()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_conversation_profile( + conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].conversation_profile + mock_val = gcd_conversation_profile.ConversationProfile(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_conversation_profile_flattened_error_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_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_conversation_profile( + gcd_conversation_profile.UpdateConversationProfileRequest(), + conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_conversation_profile(transport: str = 'grpc', request_type=conversation_profile.DeleteConversationProfileRequest): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == conversation_profile.DeleteConversationProfileRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_conversation_profile_from_dict(): + test_delete_conversation_profile(request_type=dict) + + +def test_delete_conversation_profile_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationProfilesClient( + credentials=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_conversation_profile), + '__call__') as call: + client.delete_conversation_profile() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversation_profile.DeleteConversationProfileRequest() + + +@pytest.mark.asyncio +async def test_delete_conversation_profile_async(transport: str = 'grpc_asyncio', request_type=conversation_profile.DeleteConversationProfileRequest): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation_profile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversation_profile.DeleteConversationProfileRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_conversation_profile_async_from_dict(): + await test_delete_conversation_profile_async(request_type=dict) + + +def test_delete_conversation_profile_field_headers(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation_profile.DeleteConversationProfileRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation_profile), + '__call__') as call: + call.return_value = None + client.delete_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_conversation_profile_field_headers_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation_profile.DeleteConversationProfileRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation_profile), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_conversation_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_conversation_profile_flattened(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation_profile), + '__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_conversation_profile( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_conversation_profile_flattened_error(): + client = ConversationProfilesClient( + credentials=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_conversation_profile( + conversation_profile.DeleteConversationProfileRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_conversation_profile_flattened_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation_profile), + '__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_conversation_profile( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_conversation_profile_flattened_error_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_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_conversation_profile( + conversation_profile.DeleteConversationProfileRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ConversationProfilesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ConversationProfilesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConversationProfilesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ConversationProfilesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConversationProfilesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ConversationProfilesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ConversationProfilesClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ConversationProfilesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ConversationProfilesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ConversationProfilesGrpcTransport, + transports.ConversationProfilesGrpcAsyncIOTransport, +]) +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 = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ConversationProfilesGrpcTransport, + ) + +def test_conversation_profiles_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ConversationProfilesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_conversation_profiles_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2beta1.services.conversation_profiles.transports.ConversationProfilesTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ConversationProfilesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_conversation_profiles', + 'get_conversation_profile', + 'create_conversation_profile', + 'update_conversation_profile', + 'delete_conversation_profile', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_conversation_profiles_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.dialogflow_v2beta1.services.conversation_profiles.transports.ConversationProfilesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConversationProfilesTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_conversation_profiles_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.dialogflow_v2beta1.services.conversation_profiles.transports.ConversationProfilesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConversationProfilesTransport() + adc.assert_called_once() + + +def test_conversation_profiles_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) + ConversationProfilesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ConversationProfilesGrpcTransport, + transports.ConversationProfilesGrpcAsyncIOTransport, + ], +) +def test_conversation_profiles_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationProfilesGrpcTransport, grpc_helpers), + (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_conversation_profiles_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ConversationProfilesGrpcTransport, transports.ConversationProfilesGrpcAsyncIOTransport]) +def test_conversation_profiles_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_conversation_profiles_host_no_port(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_conversation_profiles_host_with_port(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_conversation_profiles_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ConversationProfilesGrpcTransport( + 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_conversation_profiles_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ConversationProfilesGrpcAsyncIOTransport( + 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.ConversationProfilesGrpcTransport, transports.ConversationProfilesGrpcAsyncIOTransport]) +def test_conversation_profiles_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.ConversationProfilesGrpcTransport, transports.ConversationProfilesGrpcAsyncIOTransport]) +def test_conversation_profiles_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_agent_path(): + project = "squid" + expected = "projects/{project}/agent".format(project=project, ) + actual = ConversationProfilesClient.agent_path(project) + assert expected == actual + + +def test_parse_agent_path(): + expected = { + "project": "clam", + } + path = ConversationProfilesClient.agent_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationProfilesClient.parse_agent_path(path) + assert expected == actual + +def test_conversation_model_path(): + project = "whelk" + location = "octopus" + conversation_model = "oyster" + expected = "projects/{project}/locations/{location}/conversationModels/{conversation_model}".format(project=project, location=location, conversation_model=conversation_model, ) + actual = ConversationProfilesClient.conversation_model_path(project, location, conversation_model) + assert expected == actual + + +def test_parse_conversation_model_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "conversation_model": "mussel", + } + path = ConversationProfilesClient.conversation_model_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationProfilesClient.parse_conversation_model_path(path) + assert expected == actual + +def test_conversation_profile_path(): + project = "winkle" + conversation_profile = "nautilus" + expected = "projects/{project}/conversationProfiles/{conversation_profile}".format(project=project, conversation_profile=conversation_profile, ) + actual = ConversationProfilesClient.conversation_profile_path(project, conversation_profile) + assert expected == actual + + +def test_parse_conversation_profile_path(): + expected = { + "project": "scallop", + "conversation_profile": "abalone", + } + path = ConversationProfilesClient.conversation_profile_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationProfilesClient.parse_conversation_profile_path(path) + assert expected == actual + +def test_cx_security_settings_path(): + project = "squid" + location = "clam" + security_settings = "whelk" + expected = "projects/{project}/locations/{location}/securitySettings/{security_settings}".format(project=project, location=location, security_settings=security_settings, ) + actual = ConversationProfilesClient.cx_security_settings_path(project, location, security_settings) + assert expected == actual + + +def test_parse_cx_security_settings_path(): + expected = { + "project": "octopus", + "location": "oyster", + "security_settings": "nudibranch", + } + path = ConversationProfilesClient.cx_security_settings_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationProfilesClient.parse_cx_security_settings_path(path) + assert expected == actual + +def test_document_path(): + project = "cuttlefish" + knowledge_base = "mussel" + document = "winkle" + expected = "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format(project=project, knowledge_base=knowledge_base, document=document, ) + actual = ConversationProfilesClient.document_path(project, knowledge_base, document) + assert expected == actual + + +def test_parse_document_path(): + expected = { + "project": "nautilus", + "knowledge_base": "scallop", + "document": "abalone", + } + path = ConversationProfilesClient.document_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationProfilesClient.parse_document_path(path) + assert expected == actual + +def test_knowledge_base_path(): + project = "squid" + knowledge_base = "clam" + expected = "projects/{project}/knowledgeBases/{knowledge_base}".format(project=project, knowledge_base=knowledge_base, ) + actual = ConversationProfilesClient.knowledge_base_path(project, knowledge_base) + assert expected == actual + + +def test_parse_knowledge_base_path(): + expected = { + "project": "whelk", + "knowledge_base": "octopus", + } + path = ConversationProfilesClient.knowledge_base_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationProfilesClient.parse_knowledge_base_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ConversationProfilesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = ConversationProfilesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationProfilesClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = ConversationProfilesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = ConversationProfilesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationProfilesClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ConversationProfilesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = ConversationProfilesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationProfilesClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = ConversationProfilesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = ConversationProfilesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationProfilesClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ConversationProfilesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = ConversationProfilesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationProfilesClient.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.ConversationProfilesTransport, '_prep_wrapped_messages') as prep: + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ConversationProfilesTransport, '_prep_wrapped_messages') as prep: + transport_class = ConversationProfilesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = ConversationProfilesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_conversations.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_conversations.py new file mode 100644 index 000000000..b817b0ebc --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_conversations.py @@ -0,0 +1,2791 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.conversations import ConversationsAsyncClient +from google.cloud.dialogflow_v2beta1.services.conversations import ConversationsClient +from google.cloud.dialogflow_v2beta1.services.conversations import pagers +from google.cloud.dialogflow_v2beta1.services.conversations import transports +from google.cloud.dialogflow_v2beta1.types import conversation +from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation +from google.cloud.dialogflow_v2beta1.types import participant +from google.cloud.dialogflow_v2beta1.types import session +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 + + +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 ConversationsClient._get_default_mtls_endpoint(None) is None + assert ConversationsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ConversationsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ConversationsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ConversationsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ConversationsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + ConversationsClient, + ConversationsAsyncClient, +]) +def test_conversations_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ConversationsGrpcTransport, "grpc"), + (transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_conversations_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + ConversationsClient, + ConversationsAsyncClient, +]) +def test_conversations_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 == 'dialogflow.googleapis.com:443' + + +def test_conversations_client_get_transport_class(): + transport = ConversationsClient.get_transport_class() + available_transports = [ + transports.ConversationsGrpcTransport, + ] + assert transport in available_transports + + transport = ConversationsClient.get_transport_class("grpc") + assert transport == transports.ConversationsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversationsClient, transports.ConversationsGrpcTransport, "grpc"), + (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ConversationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationsClient)) +@mock.patch.object(ConversationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationsAsyncClient)) +def test_conversations_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(ConversationsClient, '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(ConversationsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ConversationsClient, transports.ConversationsGrpcTransport, "grpc", "true"), + (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ConversationsClient, transports.ConversationsGrpcTransport, "grpc", "false"), + (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ConversationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationsClient)) +@mock.patch.object(ConversationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_conversations_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversationsClient, transports.ConversationsGrpcTransport, "grpc"), + (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_conversations_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversationsClient, transports.ConversationsGrpcTransport, "grpc"), + (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_conversations_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_conversations_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2beta1.services.conversations.transports.ConversationsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ConversationsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_create_conversation(transport: str = 'grpc', request_type=gcd_conversation.CreateConversationRequest): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation.Conversation( + name='name_value', + lifecycle_state=gcd_conversation.Conversation.LifecycleState.IN_PROGRESS, + conversation_profile='conversation_profile_value', + conversation_stage=gcd_conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, + ) + response = client.create_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_conversation.CreateConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation.Conversation) + assert response.name == 'name_value' + assert response.lifecycle_state == gcd_conversation.Conversation.LifecycleState.IN_PROGRESS + assert response.conversation_profile == 'conversation_profile_value' + assert response.conversation_stage == gcd_conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE + + +def test_create_conversation_from_dict(): + test_create_conversation(request_type=dict) + + +def test_create_conversation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationsClient( + credentials=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_conversation), + '__call__') as call: + client.create_conversation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_conversation.CreateConversationRequest() + + +@pytest.mark.asyncio +async def test_create_conversation_async(transport: str = 'grpc_asyncio', request_type=gcd_conversation.CreateConversationRequest): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation( + name='name_value', + lifecycle_state=gcd_conversation.Conversation.LifecycleState.IN_PROGRESS, + conversation_profile='conversation_profile_value', + conversation_stage=gcd_conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, + )) + response = await client.create_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_conversation.CreateConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation.Conversation) + assert response.name == 'name_value' + assert response.lifecycle_state == gcd_conversation.Conversation.LifecycleState.IN_PROGRESS + assert response.conversation_profile == 'conversation_profile_value' + assert response.conversation_stage == gcd_conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE + + +@pytest.mark.asyncio +async def test_create_conversation_async_from_dict(): + await test_create_conversation_async(request_type=dict) + + +def test_create_conversation_field_headers(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_conversation.CreateConversationRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation), + '__call__') as call: + call.return_value = gcd_conversation.Conversation() + client.create_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_conversation_field_headers_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_conversation.CreateConversationRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation()) + await client.create_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_conversation_flattened(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation.Conversation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_conversation( + parent='parent_value', + conversation=gcd_conversation.Conversation(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].conversation + mock_val = gcd_conversation.Conversation(name='name_value') + assert arg == mock_val + + +def test_create_conversation_flattened_error(): + client = ConversationsClient( + credentials=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_conversation( + gcd_conversation.CreateConversationRequest(), + parent='parent_value', + conversation=gcd_conversation.Conversation(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_conversation_flattened_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation.Conversation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_conversation( + parent='parent_value', + conversation=gcd_conversation.Conversation(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].conversation + mock_val = gcd_conversation.Conversation(name='name_value') + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_conversation_flattened_error_async(): + client = ConversationsAsyncClient( + credentials=ga_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_conversation( + gcd_conversation.CreateConversationRequest(), + parent='parent_value', + conversation=gcd_conversation.Conversation(name='name_value'), + ) + + +def test_list_conversations(transport: str = 'grpc', request_type=conversation.ListConversationsRequest): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.ListConversationsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.ListConversationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversationsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_conversations_from_dict(): + test_list_conversations(request_type=dict) + + +def test_list_conversations_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationsClient( + credentials=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_conversations), + '__call__') as call: + client.list_conversations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.ListConversationsRequest() + + +@pytest.mark.asyncio +async def test_list_conversations_async(transport: str = 'grpc_asyncio', request_type=conversation.ListConversationsRequest): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation.ListConversationsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.ListConversationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversationsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_conversations_async_from_dict(): + await test_list_conversations_async(request_type=dict) + + +def test_list_conversations_field_headers(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation.ListConversationsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + call.return_value = conversation.ListConversationsResponse() + client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_conversations_field_headers_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation.ListConversationsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.ListConversationsResponse()) + await client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_conversations_flattened(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.ListConversationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_conversations( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_conversations_flattened_error(): + client = ConversationsClient( + credentials=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_conversations( + conversation.ListConversationsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_conversations_flattened_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.ListConversationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.ListConversationsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_conversations( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_conversations_flattened_error_async(): + client = ConversationsAsyncClient( + credentials=ga_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_conversations( + conversation.ListConversationsRequest(), + parent='parent_value', + ) + + +def test_list_conversations_pager(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + conversation.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token='abc', + ), + conversation.ListConversationsResponse( + conversations=[], + next_page_token='def', + ), + conversation.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token='ghi', + ), + conversation.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_conversations(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, conversation.Conversation) + for i in results) + +def test_list_conversations_pages(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + conversation.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token='abc', + ), + conversation.ListConversationsResponse( + conversations=[], + next_page_token='def', + ), + conversation.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token='ghi', + ), + conversation.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_conversations(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_conversations_async_pager(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + conversation.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token='abc', + ), + conversation.ListConversationsResponse( + conversations=[], + next_page_token='def', + ), + conversation.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token='ghi', + ), + conversation.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_conversations(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, conversation.Conversation) + for i in responses) + +@pytest.mark.asyncio +async def test_list_conversations_async_pages(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + conversation.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token='abc', + ), + conversation.ListConversationsResponse( + conversations=[], + next_page_token='def', + ), + conversation.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token='ghi', + ), + conversation.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_conversations(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_conversation(transport: str = 'grpc', request_type=conversation.GetConversationRequest): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.Conversation( + name='name_value', + lifecycle_state=conversation.Conversation.LifecycleState.IN_PROGRESS, + conversation_profile='conversation_profile_value', + conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, + ) + response = client.get_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.GetConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, conversation.Conversation) + assert response.name == 'name_value' + assert response.lifecycle_state == conversation.Conversation.LifecycleState.IN_PROGRESS + assert response.conversation_profile == 'conversation_profile_value' + assert response.conversation_stage == conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE + + +def test_get_conversation_from_dict(): + test_get_conversation(request_type=dict) + + +def test_get_conversation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationsClient( + credentials=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_conversation), + '__call__') as call: + client.get_conversation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.GetConversationRequest() + + +@pytest.mark.asyncio +async def test_get_conversation_async(transport: str = 'grpc_asyncio', request_type=conversation.GetConversationRequest): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation( + name='name_value', + lifecycle_state=conversation.Conversation.LifecycleState.IN_PROGRESS, + conversation_profile='conversation_profile_value', + conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, + )) + response = await client.get_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.GetConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, conversation.Conversation) + assert response.name == 'name_value' + assert response.lifecycle_state == conversation.Conversation.LifecycleState.IN_PROGRESS + assert response.conversation_profile == 'conversation_profile_value' + assert response.conversation_stage == conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE + + +@pytest.mark.asyncio +async def test_get_conversation_async_from_dict(): + await test_get_conversation_async(request_type=dict) + + +def test_get_conversation_field_headers(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation.GetConversationRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation), + '__call__') as call: + call.return_value = conversation.Conversation() + client.get_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_conversation_field_headers_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation.GetConversationRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) + await client.get_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_conversation_flattened(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.Conversation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_conversation( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_conversation_flattened_error(): + client = ConversationsClient( + credentials=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_conversation( + conversation.GetConversationRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_conversation_flattened_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.Conversation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_conversation( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_conversation_flattened_error_async(): + client = ConversationsAsyncClient( + credentials=ga_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_conversation( + conversation.GetConversationRequest(), + name='name_value', + ) + + +def test_complete_conversation(transport: str = 'grpc', request_type=conversation.CompleteConversationRequest): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.Conversation( + name='name_value', + lifecycle_state=conversation.Conversation.LifecycleState.IN_PROGRESS, + conversation_profile='conversation_profile_value', + conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, + ) + response = client.complete_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.CompleteConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, conversation.Conversation) + assert response.name == 'name_value' + assert response.lifecycle_state == conversation.Conversation.LifecycleState.IN_PROGRESS + assert response.conversation_profile == 'conversation_profile_value' + assert response.conversation_stage == conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE + + +def test_complete_conversation_from_dict(): + test_complete_conversation(request_type=dict) + + +def test_complete_conversation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_conversation), + '__call__') as call: + client.complete_conversation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.CompleteConversationRequest() + + +@pytest.mark.asyncio +async def test_complete_conversation_async(transport: str = 'grpc_asyncio', request_type=conversation.CompleteConversationRequest): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation( + name='name_value', + lifecycle_state=conversation.Conversation.LifecycleState.IN_PROGRESS, + conversation_profile='conversation_profile_value', + conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, + )) + response = await client.complete_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.CompleteConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, conversation.Conversation) + assert response.name == 'name_value' + assert response.lifecycle_state == conversation.Conversation.LifecycleState.IN_PROGRESS + assert response.conversation_profile == 'conversation_profile_value' + assert response.conversation_stage == conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE + + +@pytest.mark.asyncio +async def test_complete_conversation_async_from_dict(): + await test_complete_conversation_async(request_type=dict) + + +def test_complete_conversation_field_headers(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation.CompleteConversationRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_conversation), + '__call__') as call: + call.return_value = conversation.Conversation() + client.complete_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_complete_conversation_field_headers_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation.CompleteConversationRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_conversation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) + await client.complete_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_complete_conversation_flattened(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.Conversation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.complete_conversation( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_complete_conversation_flattened_error(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.complete_conversation( + conversation.CompleteConversationRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_complete_conversation_flattened_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.Conversation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.complete_conversation( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_complete_conversation_flattened_error_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.complete_conversation( + conversation.CompleteConversationRequest(), + name='name_value', + ) + + +def test_batch_create_messages(transport: str = 'grpc', request_type=conversation.BatchCreateMessagesRequest): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_messages), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.BatchCreateMessagesResponse( + ) + response = client.batch_create_messages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.BatchCreateMessagesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, conversation.BatchCreateMessagesResponse) + + +def test_batch_create_messages_from_dict(): + test_batch_create_messages(request_type=dict) + + +def test_batch_create_messages_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_messages), + '__call__') as call: + client.batch_create_messages() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.BatchCreateMessagesRequest() + + +@pytest.mark.asyncio +async def test_batch_create_messages_async(transport: str = 'grpc_asyncio', request_type=conversation.BatchCreateMessagesRequest): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_messages), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation.BatchCreateMessagesResponse( + )) + response = await client.batch_create_messages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.BatchCreateMessagesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, conversation.BatchCreateMessagesResponse) + + +@pytest.mark.asyncio +async def test_batch_create_messages_async_from_dict(): + await test_batch_create_messages_async(request_type=dict) + + +def test_batch_create_messages_field_headers(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation.BatchCreateMessagesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_messages), + '__call__') as call: + call.return_value = conversation.BatchCreateMessagesResponse() + client.batch_create_messages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_batch_create_messages_field_headers_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation.BatchCreateMessagesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_messages), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.BatchCreateMessagesResponse()) + await client.batch_create_messages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_batch_create_messages_flattened(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_messages), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.BatchCreateMessagesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_create_messages( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_batch_create_messages_flattened_error(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_create_messages( + conversation.BatchCreateMessagesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_batch_create_messages_flattened_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_messages), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.BatchCreateMessagesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.BatchCreateMessagesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_create_messages( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_batch_create_messages_flattened_error_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_create_messages( + conversation.BatchCreateMessagesRequest(), + parent='parent_value', + ) + + +def test_list_messages(transport: str = 'grpc', request_type=conversation.ListMessagesRequest): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_messages), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.ListMessagesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_messages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.ListMessagesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMessagesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_messages_from_dict(): + test_list_messages(request_type=dict) + + +def test_list_messages_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationsClient( + credentials=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_messages), + '__call__') as call: + client.list_messages() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.ListMessagesRequest() + + +@pytest.mark.asyncio +async def test_list_messages_async(transport: str = 'grpc_asyncio', request_type=conversation.ListMessagesRequest): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_messages), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation.ListMessagesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_messages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversation.ListMessagesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMessagesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_messages_async_from_dict(): + await test_list_messages_async(request_type=dict) + + +def test_list_messages_field_headers(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation.ListMessagesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_messages), + '__call__') as call: + call.return_value = conversation.ListMessagesResponse() + client.list_messages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_messages_field_headers_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversation.ListMessagesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_messages), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.ListMessagesResponse()) + await client.list_messages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_messages_flattened(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_messages), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.ListMessagesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_messages( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_messages_flattened_error(): + client = ConversationsClient( + credentials=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_messages( + conversation.ListMessagesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_messages_flattened_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_messages), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.ListMessagesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.ListMessagesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_messages( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_messages_flattened_error_async(): + client = ConversationsAsyncClient( + credentials=ga_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_messages( + conversation.ListMessagesRequest(), + parent='parent_value', + ) + + +def test_list_messages_pager(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_messages), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + conversation.ListMessagesResponse( + messages=[ + participant.Message(), + participant.Message(), + participant.Message(), + ], + next_page_token='abc', + ), + conversation.ListMessagesResponse( + messages=[], + next_page_token='def', + ), + conversation.ListMessagesResponse( + messages=[ + participant.Message(), + ], + next_page_token='ghi', + ), + conversation.ListMessagesResponse( + messages=[ + participant.Message(), + participant.Message(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_messages(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, participant.Message) + for i in results) + +def test_list_messages_pages(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_messages), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + conversation.ListMessagesResponse( + messages=[ + participant.Message(), + participant.Message(), + participant.Message(), + ], + next_page_token='abc', + ), + conversation.ListMessagesResponse( + messages=[], + next_page_token='def', + ), + conversation.ListMessagesResponse( + messages=[ + participant.Message(), + ], + next_page_token='ghi', + ), + conversation.ListMessagesResponse( + messages=[ + participant.Message(), + participant.Message(), + ], + ), + RuntimeError, + ) + pages = list(client.list_messages(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_messages_async_pager(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_messages), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + conversation.ListMessagesResponse( + messages=[ + participant.Message(), + participant.Message(), + participant.Message(), + ], + next_page_token='abc', + ), + conversation.ListMessagesResponse( + messages=[], + next_page_token='def', + ), + conversation.ListMessagesResponse( + messages=[ + participant.Message(), + ], + next_page_token='ghi', + ), + conversation.ListMessagesResponse( + messages=[ + participant.Message(), + participant.Message(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_messages(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, participant.Message) + for i in responses) + +@pytest.mark.asyncio +async def test_list_messages_async_pages(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_messages), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + conversation.ListMessagesResponse( + messages=[ + participant.Message(), + participant.Message(), + participant.Message(), + ], + next_page_token='abc', + ), + conversation.ListMessagesResponse( + messages=[], + next_page_token='def', + ), + conversation.ListMessagesResponse( + messages=[ + participant.Message(), + ], + next_page_token='ghi', + ), + conversation.ListMessagesResponse( + messages=[ + participant.Message(), + participant.Message(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_messages(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.ConversationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ConversationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConversationsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ConversationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConversationsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ConversationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ConversationsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ConversationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ConversationsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ConversationsGrpcTransport, + transports.ConversationsGrpcAsyncIOTransport, +]) +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 = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ConversationsGrpcTransport, + ) + +def test_conversations_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ConversationsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_conversations_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2beta1.services.conversations.transports.ConversationsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ConversationsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_conversation', + 'list_conversations', + 'get_conversation', + 'complete_conversation', + 'batch_create_messages', + 'list_messages', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_conversations_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.dialogflow_v2beta1.services.conversations.transports.ConversationsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConversationsTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_conversations_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.dialogflow_v2beta1.services.conversations.transports.ConversationsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConversationsTransport() + adc.assert_called_once() + + +def test_conversations_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) + ConversationsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ConversationsGrpcTransport, + transports.ConversationsGrpcAsyncIOTransport, + ], +) +def test_conversations_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationsGrpcTransport, grpc_helpers), + (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_conversations_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ConversationsGrpcTransport, transports.ConversationsGrpcAsyncIOTransport]) +def test_conversations_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_conversations_host_no_port(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_conversations_host_with_port(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_conversations_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ConversationsGrpcTransport( + 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_conversations_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ConversationsGrpcAsyncIOTransport( + 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.ConversationsGrpcTransport, transports.ConversationsGrpcAsyncIOTransport]) +def test_conversations_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.ConversationsGrpcTransport, transports.ConversationsGrpcAsyncIOTransport]) +def test_conversations_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_conversation_path(): + project = "squid" + conversation = "clam" + expected = "projects/{project}/conversations/{conversation}".format(project=project, conversation=conversation, ) + actual = ConversationsClient.conversation_path(project, conversation) + assert expected == actual + + +def test_parse_conversation_path(): + expected = { + "project": "whelk", + "conversation": "octopus", + } + path = ConversationsClient.conversation_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationsClient.parse_conversation_path(path) + assert expected == actual + +def test_conversation_profile_path(): + project = "oyster" + conversation_profile = "nudibranch" + expected = "projects/{project}/conversationProfiles/{conversation_profile}".format(project=project, conversation_profile=conversation_profile, ) + actual = ConversationsClient.conversation_profile_path(project, conversation_profile) + assert expected == actual + + +def test_parse_conversation_profile_path(): + expected = { + "project": "cuttlefish", + "conversation_profile": "mussel", + } + path = ConversationsClient.conversation_profile_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationsClient.parse_conversation_profile_path(path) + assert expected == actual + +def test_message_path(): + project = "winkle" + conversation = "nautilus" + message = "scallop" + expected = "projects/{project}/conversations/{conversation}/messages/{message}".format(project=project, conversation=conversation, message=message, ) + actual = ConversationsClient.message_path(project, conversation, message) + assert expected == actual + + +def test_parse_message_path(): + expected = { + "project": "abalone", + "conversation": "squid", + "message": "clam", + } + path = ConversationsClient.message_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationsClient.parse_message_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ConversationsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = ConversationsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = ConversationsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = ConversationsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ConversationsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = ConversationsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = ConversationsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = ConversationsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationsClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ConversationsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = ConversationsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationsClient.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.ConversationsTransport, '_prep_wrapped_messages') as prep: + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ConversationsTransport, '_prep_wrapped_messages') as prep: + transport_class = ConversationsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = ConversationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_documents.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_documents.py new file mode 100644 index 000000000..454302383 --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_documents.py @@ -0,0 +1,2751 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.documents import DocumentsAsyncClient +from google.cloud.dialogflow_v2beta1.services.documents import DocumentsClient +from google.cloud.dialogflow_v2beta1.services.documents import pagers +from google.cloud.dialogflow_v2beta1.services.documents import transports +from google.cloud.dialogflow_v2beta1.types import document +from google.cloud.dialogflow_v2beta1.types import document as gcd_document +from google.cloud.dialogflow_v2beta1.types import gcs +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert DocumentsClient._get_default_mtls_endpoint(None) is None + assert DocumentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert DocumentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert DocumentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert DocumentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert DocumentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + DocumentsClient, + DocumentsAsyncClient, +]) +def test_documents_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.DocumentsGrpcTransport, "grpc"), + (transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_documents_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + DocumentsClient, + DocumentsAsyncClient, +]) +def test_documents_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 == 'dialogflow.googleapis.com:443' + + +def test_documents_client_get_transport_class(): + transport = DocumentsClient.get_transport_class() + available_transports = [ + transports.DocumentsGrpcTransport, + ] + assert transport in available_transports + + transport = DocumentsClient.get_transport_class("grpc") + assert transport == transports.DocumentsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DocumentsClient, transports.DocumentsGrpcTransport, "grpc"), + (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(DocumentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentsClient)) +@mock.patch.object(DocumentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentsAsyncClient)) +def test_documents_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(DocumentsClient, '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(DocumentsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (DocumentsClient, transports.DocumentsGrpcTransport, "grpc", "true"), + (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DocumentsClient, transports.DocumentsGrpcTransport, "grpc", "false"), + (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(DocumentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentsClient)) +@mock.patch.object(DocumentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_documents_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DocumentsClient, transports.DocumentsGrpcTransport, "grpc"), + (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_documents_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DocumentsClient, transports.DocumentsGrpcTransport, "grpc"), + (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_documents_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_documents_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2beta1.services.documents.transports.DocumentsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = DocumentsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_documents(transport: str = 'grpc', request_type=document.ListDocumentsRequest): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document.ListDocumentsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document.ListDocumentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDocumentsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_documents_from_dict(): + test_list_documents(request_type=dict) + + +def test_list_documents_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentsClient( + credentials=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_documents), + '__call__') as call: + client.list_documents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document.ListDocumentsRequest() + + +@pytest.mark.asyncio +async def test_list_documents_async(transport: str = 'grpc_asyncio', request_type=document.ListDocumentsRequest): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document.ListDocumentsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document.ListDocumentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDocumentsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_documents_async_from_dict(): + await test_list_documents_async(request_type=dict) + + +def test_list_documents_field_headers(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document.ListDocumentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + call.return_value = document.ListDocumentsResponse() + client.list_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_documents_field_headers_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document.ListDocumentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.ListDocumentsResponse()) + await client.list_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_documents_flattened(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document.ListDocumentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_documents( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_documents_flattened_error(): + client = DocumentsClient( + credentials=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_documents( + document.ListDocumentsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_documents_flattened_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document.ListDocumentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.ListDocumentsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_documents( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_documents_flattened_error_async(): + client = DocumentsAsyncClient( + credentials=ga_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_documents( + document.ListDocumentsRequest(), + parent='parent_value', + ) + + +def test_list_documents_pager(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + document.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + document.Document(), + ], + next_page_token='abc', + ), + document.ListDocumentsResponse( + documents=[], + next_page_token='def', + ), + document.ListDocumentsResponse( + documents=[ + document.Document(), + ], + next_page_token='ghi', + ), + document.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_documents(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, document.Document) + for i in results) + +def test_list_documents_pages(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + document.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + document.Document(), + ], + next_page_token='abc', + ), + document.ListDocumentsResponse( + documents=[], + next_page_token='def', + ), + document.ListDocumentsResponse( + documents=[ + document.Document(), + ], + next_page_token='ghi', + ), + document.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + ], + ), + RuntimeError, + ) + pages = list(client.list_documents(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_documents_async_pager(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + document.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + document.Document(), + ], + next_page_token='abc', + ), + document.ListDocumentsResponse( + documents=[], + next_page_token='def', + ), + document.ListDocumentsResponse( + documents=[ + document.Document(), + ], + next_page_token='ghi', + ), + document.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_documents(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, document.Document) + for i in responses) + +@pytest.mark.asyncio +async def test_list_documents_async_pages(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + document.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + document.Document(), + ], + next_page_token='abc', + ), + document.ListDocumentsResponse( + documents=[], + next_page_token='def', + ), + document.ListDocumentsResponse( + documents=[ + document.Document(), + ], + next_page_token='ghi', + ), + document.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_documents(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_document(transport: str = 'grpc', request_type=document.GetDocumentRequest): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document.Document( + name='name_value', + display_name='display_name_value', + mime_type='mime_type_value', + knowledge_types=[document.Document.KnowledgeType.FAQ], + enable_auto_reload=True, + content_uri='content_uri_value', + ) + response = client.get_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document.GetDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, document.Document) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.mime_type == 'mime_type_value' + assert response.knowledge_types == [document.Document.KnowledgeType.FAQ] + assert response.enable_auto_reload is True + + +def test_get_document_from_dict(): + test_get_document(request_type=dict) + + +def test_get_document_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentsClient( + credentials=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_document), + '__call__') as call: + client.get_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document.GetDocumentRequest() + + +@pytest.mark.asyncio +async def test_get_document_async(transport: str = 'grpc_asyncio', request_type=document.GetDocumentRequest): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document.Document( + name='name_value', + display_name='display_name_value', + mime_type='mime_type_value', + knowledge_types=[document.Document.KnowledgeType.FAQ], + enable_auto_reload=True, + )) + response = await client.get_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document.GetDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, document.Document) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.mime_type == 'mime_type_value' + assert response.knowledge_types == [document.Document.KnowledgeType.FAQ] + assert response.enable_auto_reload is True + + +@pytest.mark.asyncio +async def test_get_document_async_from_dict(): + await test_get_document_async(request_type=dict) + + +def test_get_document_field_headers(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document.GetDocumentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_document), + '__call__') as call: + call.return_value = document.Document() + client.get_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_document_field_headers_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document.GetDocumentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) + await client.get_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_document_flattened(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document.Document() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_document( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_document_flattened_error(): + client = DocumentsClient( + credentials=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_document( + document.GetDocumentRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_document_flattened_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document.Document() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_document( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_document_flattened_error_async(): + client = DocumentsAsyncClient( + credentials=ga_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_document( + document.GetDocumentRequest(), + name='name_value', + ) + + +def test_create_document(transport: str = 'grpc', request_type=gcd_document.CreateDocumentRequest): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_document.CreateDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_document_from_dict(): + test_create_document(request_type=dict) + + +def test_create_document_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentsClient( + credentials=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_document), + '__call__') as call: + client.create_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_document.CreateDocumentRequest() + + +@pytest.mark.asyncio +async def test_create_document_async(transport: str = 'grpc_asyncio', request_type=gcd_document.CreateDocumentRequest): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_document.CreateDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_document_async_from_dict(): + await test_create_document_async(request_type=dict) + + +def test_create_document_field_headers(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_document.CreateDocumentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_document), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_document_field_headers_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_document.CreateDocumentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_document_flattened(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_document( + parent='parent_value', + document=gcd_document.Document(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].document + mock_val = gcd_document.Document(name='name_value') + assert arg == mock_val + + +def test_create_document_flattened_error(): + client = DocumentsClient( + credentials=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_document( + gcd_document.CreateDocumentRequest(), + parent='parent_value', + document=gcd_document.Document(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_document_flattened_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_document( + parent='parent_value', + document=gcd_document.Document(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].document + mock_val = gcd_document.Document(name='name_value') + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_document_flattened_error_async(): + client = DocumentsAsyncClient( + credentials=ga_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_document( + gcd_document.CreateDocumentRequest(), + parent='parent_value', + document=gcd_document.Document(name='name_value'), + ) + + +def test_import_documents(transport: str = 'grpc', request_type=document.ImportDocumentsRequest): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document.ImportDocumentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_documents_from_dict(): + test_import_documents(request_type=dict) + + +def test_import_documents_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentsClient( + credentials=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_documents), + '__call__') as call: + client.import_documents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document.ImportDocumentsRequest() + + +@pytest.mark.asyncio +async def test_import_documents_async(transport: str = 'grpc_asyncio', request_type=document.ImportDocumentsRequest): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_documents), + '__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_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document.ImportDocumentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_documents_async_from_dict(): + await test_import_documents_async(request_type=dict) + + +def test_import_documents_field_headers(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document.ImportDocumentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_documents), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_documents_field_headers_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document.ImportDocumentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_documents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_delete_document(transport: str = 'grpc', request_type=document.DeleteDocumentRequest): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document.DeleteDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_document_from_dict(): + test_delete_document(request_type=dict) + + +def test_delete_document_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentsClient( + credentials=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_document), + '__call__') as call: + client.delete_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document.DeleteDocumentRequest() + + +@pytest.mark.asyncio +async def test_delete_document_async(transport: str = 'grpc_asyncio', request_type=document.DeleteDocumentRequest): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document.DeleteDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_document_async_from_dict(): + await test_delete_document_async(request_type=dict) + + +def test_delete_document_field_headers(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document.DeleteDocumentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_document), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_document_field_headers_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document.DeleteDocumentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_document_flattened(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_document( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_document_flattened_error(): + client = DocumentsClient( + credentials=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_document( + document.DeleteDocumentRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_document_flattened_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_document( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_document_flattened_error_async(): + client = DocumentsAsyncClient( + credentials=ga_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_document( + document.DeleteDocumentRequest(), + name='name_value', + ) + + +def test_update_document(transport: str = 'grpc', request_type=gcd_document.UpdateDocumentRequest): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_document.UpdateDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_document_from_dict(): + test_update_document(request_type=dict) + + +def test_update_document_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentsClient( + credentials=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_document), + '__call__') as call: + client.update_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_document.UpdateDocumentRequest() + + +@pytest.mark.asyncio +async def test_update_document_async(transport: str = 'grpc_asyncio', request_type=gcd_document.UpdateDocumentRequest): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_document.UpdateDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_document_async_from_dict(): + await test_update_document_async(request_type=dict) + + +def test_update_document_field_headers(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_document.UpdateDocumentRequest() + + request.document.name = 'document.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_document), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'document.name=document.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_document_field_headers_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_document.UpdateDocumentRequest() + + request.document.name = 'document.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'document.name=document.name/value', + ) in kw['metadata'] + + +def test_update_document_flattened(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_document( + document=gcd_document.Document(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].document + mock_val = gcd_document.Document(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_document_flattened_error(): + client = DocumentsClient( + credentials=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_document( + gcd_document.UpdateDocumentRequest(), + document=gcd_document.Document(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_document_flattened_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_document( + document=gcd_document.Document(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].document + mock_val = gcd_document.Document(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_document_flattened_error_async(): + client = DocumentsAsyncClient( + credentials=ga_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_document( + gcd_document.UpdateDocumentRequest(), + document=gcd_document.Document(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_reload_document(transport: str = 'grpc', request_type=document.ReloadDocumentRequest): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reload_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.reload_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document.ReloadDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_reload_document_from_dict(): + test_reload_document(request_type=dict) + + +def test_reload_document_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reload_document), + '__call__') as call: + client.reload_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document.ReloadDocumentRequest() + + +@pytest.mark.asyncio +async def test_reload_document_async(transport: str = 'grpc_asyncio', request_type=document.ReloadDocumentRequest): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reload_document), + '__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.reload_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document.ReloadDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_reload_document_async_from_dict(): + await test_reload_document_async(request_type=dict) + + +def test_reload_document_field_headers(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document.ReloadDocumentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reload_document), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.reload_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_reload_document_field_headers_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document.ReloadDocumentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reload_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.reload_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_reload_document_flattened(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reload_document), + '__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.reload_document( + name='name_value', + gcs_source=gcs.GcsSource(uri='uri_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + assert args[0].gcs_source == gcs.GcsSource(uri='uri_value') + + +def test_reload_document_flattened_error(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.reload_document( + document.ReloadDocumentRequest(), + name='name_value', + gcs_source=gcs.GcsSource(uri='uri_value'), + ) + + +@pytest.mark.asyncio +async def test_reload_document_flattened_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reload_document), + '__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.reload_document( + name='name_value', + gcs_source=gcs.GcsSource(uri='uri_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + assert args[0].gcs_source == gcs.GcsSource(uri='uri_value') + + +@pytest.mark.asyncio +async def test_reload_document_flattened_error_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.reload_document( + document.ReloadDocumentRequest(), + name='name_value', + gcs_source=gcs.GcsSource(uri='uri_value'), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DocumentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DocumentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DocumentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DocumentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DocumentsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DocumentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DocumentsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DocumentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DocumentsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.DocumentsGrpcTransport, + transports.DocumentsGrpcAsyncIOTransport, +]) +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 = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DocumentsGrpcTransport, + ) + +def test_documents_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DocumentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_documents_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2beta1.services.documents.transports.DocumentsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.DocumentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_documents', + 'get_document', + 'create_document', + 'import_documents', + 'delete_document', + 'update_document', + 'reload_document', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +def test_documents_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.dialogflow_v2beta1.services.documents.transports.DocumentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DocumentsTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_documents_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.dialogflow_v2beta1.services.documents.transports.DocumentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DocumentsTransport() + adc.assert_called_once() + + +def test_documents_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) + DocumentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DocumentsGrpcTransport, + transports.DocumentsGrpcAsyncIOTransport, + ], +) +def test_documents_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DocumentsGrpcTransport, grpc_helpers), + (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_documents_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.DocumentsGrpcTransport, transports.DocumentsGrpcAsyncIOTransport]) +def test_documents_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_documents_host_no_port(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_documents_host_with_port(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_documents_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DocumentsGrpcTransport( + 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_documents_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DocumentsGrpcAsyncIOTransport( + 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.DocumentsGrpcTransport, transports.DocumentsGrpcAsyncIOTransport]) +def test_documents_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.DocumentsGrpcTransport, transports.DocumentsGrpcAsyncIOTransport]) +def test_documents_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_documents_grpc_lro_client(): + client = DocumentsClient( + 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_documents_grpc_lro_async_client(): + client = DocumentsAsyncClient( + 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_document_path(): + project = "squid" + knowledge_base = "clam" + document = "whelk" + expected = "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format(project=project, knowledge_base=knowledge_base, document=document, ) + actual = DocumentsClient.document_path(project, knowledge_base, document) + assert expected == actual + + +def test_parse_document_path(): + expected = { + "project": "octopus", + "knowledge_base": "oyster", + "document": "nudibranch", + } + path = DocumentsClient.document_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentsClient.parse_document_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = DocumentsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = DocumentsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = DocumentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = DocumentsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DocumentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = DocumentsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = DocumentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = DocumentsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentsClient.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 = DocumentsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = DocumentsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentsClient.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.DocumentsTransport, '_prep_wrapped_messages') as prep: + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.DocumentsTransport, '_prep_wrapped_messages') as prep: + transport_class = DocumentsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = DocumentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = DocumentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_entity_types.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_entity_types.py new file mode 100644 index 000000000..15be1097e --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_entity_types.py @@ -0,0 +1,3583 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.entity_types import EntityTypesAsyncClient +from google.cloud.dialogflow_v2beta1.services.entity_types import EntityTypesClient +from google.cloud.dialogflow_v2beta1.services.entity_types import pagers +from google.cloud.dialogflow_v2beta1.services.entity_types import transports +from google.cloud.dialogflow_v2beta1.types import entity_type +from google.cloud.dialogflow_v2beta1.types import entity_type as gcd_entity_type +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 struct_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert EntityTypesClient._get_default_mtls_endpoint(None) is None + assert EntityTypesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert EntityTypesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert EntityTypesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert EntityTypesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert EntityTypesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + EntityTypesClient, + EntityTypesAsyncClient, +]) +def test_entity_types_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.EntityTypesGrpcTransport, "grpc"), + (transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_entity_types_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + EntityTypesClient, + EntityTypesAsyncClient, +]) +def test_entity_types_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 == 'dialogflow.googleapis.com:443' + + +def test_entity_types_client_get_transport_class(): + transport = EntityTypesClient.get_transport_class() + available_transports = [ + transports.EntityTypesGrpcTransport, + ] + assert transport in available_transports + + transport = EntityTypesClient.get_transport_class("grpc") + assert transport == transports.EntityTypesGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc"), + (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(EntityTypesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EntityTypesClient)) +@mock.patch.object(EntityTypesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EntityTypesAsyncClient)) +def test_entity_types_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(EntityTypesClient, '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(EntityTypesClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc", "true"), + (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc", "false"), + (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(EntityTypesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EntityTypesClient)) +@mock.patch.object(EntityTypesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EntityTypesAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_entity_types_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc"), + (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_entity_types_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc"), + (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_entity_types_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_entity_types_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2beta1.services.entity_types.transports.EntityTypesGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = EntityTypesClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_entity_types(transport: str = 'grpc', request_type=entity_type.ListEntityTypesRequest): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = entity_type.ListEntityTypesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.ListEntityTypesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEntityTypesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_entity_types_from_dict(): + test_list_entity_types(request_type=dict) + + +def test_list_entity_types_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EntityTypesClient( + credentials=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_entity_types), + '__call__') as call: + client.list_entity_types() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.ListEntityTypesRequest() + + +@pytest.mark.asyncio +async def test_list_entity_types_async(transport: str = 'grpc_asyncio', request_type=entity_type.ListEntityTypesRequest): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(entity_type.ListEntityTypesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.ListEntityTypesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEntityTypesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_entity_types_async_from_dict(): + await test_list_entity_types_async(request_type=dict) + + +def test_list_entity_types_field_headers(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.ListEntityTypesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entity_types), + '__call__') as call: + call.return_value = entity_type.ListEntityTypesResponse() + client.list_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_entity_types_field_headers_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.ListEntityTypesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entity_types), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(entity_type.ListEntityTypesResponse()) + await client.list_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_entity_types_flattened(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = entity_type.ListEntityTypesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_entity_types( + parent='parent_value', + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +def test_list_entity_types_flattened_error(): + client = EntityTypesClient( + credentials=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_entity_types( + entity_type.ListEntityTypesRequest(), + parent='parent_value', + language_code='language_code_value', + ) + + +@pytest.mark.asyncio +async def test_list_entity_types_flattened_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = entity_type.ListEntityTypesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(entity_type.ListEntityTypesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_entity_types( + parent='parent_value', + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_entity_types_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=ga_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_entity_types( + entity_type.ListEntityTypesRequest(), + parent='parent_value', + language_code='language_code_value', + ) + + +def test_list_entity_types_pager(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entity_types), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + entity_type.ListEntityTypesResponse( + entity_types=[ + entity_type.EntityType(), + entity_type.EntityType(), + entity_type.EntityType(), + ], + next_page_token='abc', + ), + entity_type.ListEntityTypesResponse( + entity_types=[], + next_page_token='def', + ), + entity_type.ListEntityTypesResponse( + entity_types=[ + entity_type.EntityType(), + ], + next_page_token='ghi', + ), + entity_type.ListEntityTypesResponse( + entity_types=[ + entity_type.EntityType(), + entity_type.EntityType(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_entity_types(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, entity_type.EntityType) + for i in results) + +def test_list_entity_types_pages(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entity_types), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + entity_type.ListEntityTypesResponse( + entity_types=[ + entity_type.EntityType(), + entity_type.EntityType(), + entity_type.EntityType(), + ], + next_page_token='abc', + ), + entity_type.ListEntityTypesResponse( + entity_types=[], + next_page_token='def', + ), + entity_type.ListEntityTypesResponse( + entity_types=[ + entity_type.EntityType(), + ], + next_page_token='ghi', + ), + entity_type.ListEntityTypesResponse( + entity_types=[ + entity_type.EntityType(), + entity_type.EntityType(), + ], + ), + RuntimeError, + ) + pages = list(client.list_entity_types(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_entity_types_async_pager(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entity_types), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + entity_type.ListEntityTypesResponse( + entity_types=[ + entity_type.EntityType(), + entity_type.EntityType(), + entity_type.EntityType(), + ], + next_page_token='abc', + ), + entity_type.ListEntityTypesResponse( + entity_types=[], + next_page_token='def', + ), + entity_type.ListEntityTypesResponse( + entity_types=[ + entity_type.EntityType(), + ], + next_page_token='ghi', + ), + entity_type.ListEntityTypesResponse( + entity_types=[ + entity_type.EntityType(), + entity_type.EntityType(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_entity_types(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, entity_type.EntityType) + for i in responses) + +@pytest.mark.asyncio +async def test_list_entity_types_async_pages(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_entity_types), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + entity_type.ListEntityTypesResponse( + entity_types=[ + entity_type.EntityType(), + entity_type.EntityType(), + entity_type.EntityType(), + ], + next_page_token='abc', + ), + entity_type.ListEntityTypesResponse( + entity_types=[], + next_page_token='def', + ), + entity_type.ListEntityTypesResponse( + entity_types=[ + entity_type.EntityType(), + ], + next_page_token='ghi', + ), + entity_type.ListEntityTypesResponse( + entity_types=[ + entity_type.EntityType(), + entity_type.EntityType(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_entity_types(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_entity_type(transport: str = 'grpc', request_type=entity_type.GetEntityTypeRequest): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = entity_type.EntityType( + name='name_value', + display_name='display_name_value', + kind=entity_type.EntityType.Kind.KIND_MAP, + auto_expansion_mode=entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, + enable_fuzzy_extraction=True, + ) + response = client.get_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.GetEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, entity_type.EntityType) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.kind == entity_type.EntityType.Kind.KIND_MAP + assert response.auto_expansion_mode == entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT + assert response.enable_fuzzy_extraction is True + + +def test_get_entity_type_from_dict(): + test_get_entity_type(request_type=dict) + + +def test_get_entity_type_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EntityTypesClient( + credentials=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_entity_type), + '__call__') as call: + client.get_entity_type() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.GetEntityTypeRequest() + + +@pytest.mark.asyncio +async def test_get_entity_type_async(transport: str = 'grpc_asyncio', request_type=entity_type.GetEntityTypeRequest): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(entity_type.EntityType( + name='name_value', + display_name='display_name_value', + kind=entity_type.EntityType.Kind.KIND_MAP, + auto_expansion_mode=entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, + enable_fuzzy_extraction=True, + )) + response = await client.get_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.GetEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, entity_type.EntityType) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.kind == entity_type.EntityType.Kind.KIND_MAP + assert response.auto_expansion_mode == entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT + assert response.enable_fuzzy_extraction is True + + +@pytest.mark.asyncio +async def test_get_entity_type_async_from_dict(): + await test_get_entity_type_async(request_type=dict) + + +def test_get_entity_type_field_headers(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.GetEntityTypeRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_entity_type), + '__call__') as call: + call.return_value = entity_type.EntityType() + client.get_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_entity_type_field_headers_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.GetEntityTypeRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_entity_type), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(entity_type.EntityType()) + await client.get_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_entity_type_flattened(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = entity_type.EntityType() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_entity_type( + name='name_value', + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +def test_get_entity_type_flattened_error(): + client = EntityTypesClient( + credentials=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_entity_type( + entity_type.GetEntityTypeRequest(), + name='name_value', + language_code='language_code_value', + ) + + +@pytest.mark.asyncio +async def test_get_entity_type_flattened_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = entity_type.EntityType() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(entity_type.EntityType()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_entity_type( + name='name_value', + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_entity_type_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=ga_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_entity_type( + entity_type.GetEntityTypeRequest(), + name='name_value', + language_code='language_code_value', + ) + + +def test_create_entity_type(transport: str = 'grpc', request_type=gcd_entity_type.CreateEntityTypeRequest): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_entity_type.EntityType( + name='name_value', + display_name='display_name_value', + kind=gcd_entity_type.EntityType.Kind.KIND_MAP, + auto_expansion_mode=gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, + enable_fuzzy_extraction=True, + ) + response = client.create_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_entity_type.CreateEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_entity_type.EntityType) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.kind == gcd_entity_type.EntityType.Kind.KIND_MAP + assert response.auto_expansion_mode == gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT + assert response.enable_fuzzy_extraction is True + + +def test_create_entity_type_from_dict(): + test_create_entity_type(request_type=dict) + + +def test_create_entity_type_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EntityTypesClient( + credentials=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_entity_type), + '__call__') as call: + client.create_entity_type() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_entity_type.CreateEntityTypeRequest() + + +@pytest.mark.asyncio +async def test_create_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcd_entity_type.CreateEntityTypeRequest): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_entity_type.EntityType( + name='name_value', + display_name='display_name_value', + kind=gcd_entity_type.EntityType.Kind.KIND_MAP, + auto_expansion_mode=gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, + enable_fuzzy_extraction=True, + )) + response = await client.create_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_entity_type.CreateEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_entity_type.EntityType) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.kind == gcd_entity_type.EntityType.Kind.KIND_MAP + assert response.auto_expansion_mode == gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT + assert response.enable_fuzzy_extraction is True + + +@pytest.mark.asyncio +async def test_create_entity_type_async_from_dict(): + await test_create_entity_type_async(request_type=dict) + + +def test_create_entity_type_field_headers(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_entity_type.CreateEntityTypeRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_entity_type), + '__call__') as call: + call.return_value = gcd_entity_type.EntityType() + client.create_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_entity_type_field_headers_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_entity_type.CreateEntityTypeRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_entity_type), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_entity_type.EntityType()) + await client.create_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_entity_type_flattened(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_entity_type.EntityType() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_entity_type( + parent='parent_value', + entity_type=gcd_entity_type.EntityType(name='name_value'), + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].entity_type + mock_val = gcd_entity_type.EntityType(name='name_value') + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +def test_create_entity_type_flattened_error(): + client = EntityTypesClient( + credentials=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_entity_type( + gcd_entity_type.CreateEntityTypeRequest(), + parent='parent_value', + entity_type=gcd_entity_type.EntityType(name='name_value'), + language_code='language_code_value', + ) + + +@pytest.mark.asyncio +async def test_create_entity_type_flattened_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_entity_type.EntityType() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_entity_type.EntityType()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_entity_type( + parent='parent_value', + entity_type=gcd_entity_type.EntityType(name='name_value'), + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].entity_type + mock_val = gcd_entity_type.EntityType(name='name_value') + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_entity_type_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=ga_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_entity_type( + gcd_entity_type.CreateEntityTypeRequest(), + parent='parent_value', + entity_type=gcd_entity_type.EntityType(name='name_value'), + language_code='language_code_value', + ) + + +def test_update_entity_type(transport: str = 'grpc', request_type=gcd_entity_type.UpdateEntityTypeRequest): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_entity_type.EntityType( + name='name_value', + display_name='display_name_value', + kind=gcd_entity_type.EntityType.Kind.KIND_MAP, + auto_expansion_mode=gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, + enable_fuzzy_extraction=True, + ) + response = client.update_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_entity_type.UpdateEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_entity_type.EntityType) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.kind == gcd_entity_type.EntityType.Kind.KIND_MAP + assert response.auto_expansion_mode == gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT + assert response.enable_fuzzy_extraction is True + + +def test_update_entity_type_from_dict(): + test_update_entity_type(request_type=dict) + + +def test_update_entity_type_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EntityTypesClient( + credentials=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_entity_type), + '__call__') as call: + client.update_entity_type() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_entity_type.UpdateEntityTypeRequest() + + +@pytest.mark.asyncio +async def test_update_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcd_entity_type.UpdateEntityTypeRequest): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_entity_type.EntityType( + name='name_value', + display_name='display_name_value', + kind=gcd_entity_type.EntityType.Kind.KIND_MAP, + auto_expansion_mode=gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, + enable_fuzzy_extraction=True, + )) + response = await client.update_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_entity_type.UpdateEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_entity_type.EntityType) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.kind == gcd_entity_type.EntityType.Kind.KIND_MAP + assert response.auto_expansion_mode == gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT + assert response.enable_fuzzy_extraction is True + + +@pytest.mark.asyncio +async def test_update_entity_type_async_from_dict(): + await test_update_entity_type_async(request_type=dict) + + +def test_update_entity_type_field_headers(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_entity_type.UpdateEntityTypeRequest() + + request.entity_type.name = 'entity_type.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_entity_type), + '__call__') as call: + call.return_value = gcd_entity_type.EntityType() + client.update_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'entity_type.name=entity_type.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_entity_type_field_headers_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_entity_type.UpdateEntityTypeRequest() + + request.entity_type.name = 'entity_type.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_entity_type), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_entity_type.EntityType()) + await client.update_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'entity_type.name=entity_type.name/value', + ) in kw['metadata'] + + +def test_update_entity_type_flattened(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_entity_type.EntityType() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_entity_type( + entity_type=gcd_entity_type.EntityType(name='name_value'), + language_code='language_code_value', + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].entity_type + mock_val = gcd_entity_type.EntityType(name='name_value') + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_entity_type_flattened_error(): + client = EntityTypesClient( + credentials=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_entity_type( + gcd_entity_type.UpdateEntityTypeRequest(), + entity_type=gcd_entity_type.EntityType(name='name_value'), + language_code='language_code_value', + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_entity_type_flattened_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_entity_type.EntityType() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_entity_type.EntityType()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_entity_type( + entity_type=gcd_entity_type.EntityType(name='name_value'), + language_code='language_code_value', + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].entity_type + mock_val = gcd_entity_type.EntityType(name='name_value') + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_entity_type_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=ga_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_entity_type( + gcd_entity_type.UpdateEntityTypeRequest(), + entity_type=gcd_entity_type.EntityType(name='name_value'), + language_code='language_code_value', + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_entity_type(transport: str = 'grpc', request_type=entity_type.DeleteEntityTypeRequest): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.DeleteEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_entity_type_from_dict(): + test_delete_entity_type(request_type=dict) + + +def test_delete_entity_type_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EntityTypesClient( + credentials=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_entity_type), + '__call__') as call: + client.delete_entity_type() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.DeleteEntityTypeRequest() + + +@pytest.mark.asyncio +async def test_delete_entity_type_async(transport: str = 'grpc_asyncio', request_type=entity_type.DeleteEntityTypeRequest): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.DeleteEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_entity_type_async_from_dict(): + await test_delete_entity_type_async(request_type=dict) + + +def test_delete_entity_type_field_headers(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.DeleteEntityTypeRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_entity_type), + '__call__') as call: + call.return_value = None + client.delete_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_entity_type_field_headers_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.DeleteEntityTypeRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_entity_type), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_entity_type_flattened(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_entity_type), + '__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_entity_type( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_entity_type_flattened_error(): + client = EntityTypesClient( + credentials=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_entity_type( + entity_type.DeleteEntityTypeRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_entity_type_flattened_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_entity_type), + '__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_entity_type( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_entity_type_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=ga_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_entity_type( + entity_type.DeleteEntityTypeRequest(), + name='name_value', + ) + + +def test_batch_update_entity_types(transport: str = 'grpc', request_type=entity_type.BatchUpdateEntityTypesRequest): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.batch_update_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchUpdateEntityTypesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_update_entity_types_from_dict(): + test_batch_update_entity_types(request_type=dict) + + +def test_batch_update_entity_types_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_entity_types), + '__call__') as call: + client.batch_update_entity_types() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchUpdateEntityTypesRequest() + + +@pytest.mark.asyncio +async def test_batch_update_entity_types_async(transport: str = 'grpc_asyncio', request_type=entity_type.BatchUpdateEntityTypesRequest): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.batch_update_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchUpdateEntityTypesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_update_entity_types_async_from_dict(): + await test_batch_update_entity_types_async(request_type=dict) + + +def test_batch_update_entity_types_field_headers(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.BatchUpdateEntityTypesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_entity_types), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.batch_update_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_batch_update_entity_types_field_headers_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.BatchUpdateEntityTypesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_entity_types), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.batch_update_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_batch_delete_entity_types(transport: str = 'grpc', request_type=entity_type.BatchDeleteEntityTypesRequest): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.batch_delete_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchDeleteEntityTypesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_delete_entity_types_from_dict(): + test_batch_delete_entity_types(request_type=dict) + + +def test_batch_delete_entity_types_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entity_types), + '__call__') as call: + client.batch_delete_entity_types() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchDeleteEntityTypesRequest() + + +@pytest.mark.asyncio +async def test_batch_delete_entity_types_async(transport: str = 'grpc_asyncio', request_type=entity_type.BatchDeleteEntityTypesRequest): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.batch_delete_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchDeleteEntityTypesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_delete_entity_types_async_from_dict(): + await test_batch_delete_entity_types_async(request_type=dict) + + +def test_batch_delete_entity_types_field_headers(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.BatchDeleteEntityTypesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entity_types), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.batch_delete_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_batch_delete_entity_types_field_headers_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.BatchDeleteEntityTypesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entity_types), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.batch_delete_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_batch_delete_entity_types_flattened(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_delete_entity_types( + parent='parent_value', + entity_type_names=['entity_type_names_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].entity_type_names + mock_val = ['entity_type_names_value'] + assert arg == mock_val + + +def test_batch_delete_entity_types_flattened_error(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_delete_entity_types( + entity_type.BatchDeleteEntityTypesRequest(), + parent='parent_value', + entity_type_names=['entity_type_names_value'], + ) + + +@pytest.mark.asyncio +async def test_batch_delete_entity_types_flattened_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_delete_entity_types( + parent='parent_value', + entity_type_names=['entity_type_names_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].entity_type_names + mock_val = ['entity_type_names_value'] + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_batch_delete_entity_types_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_delete_entity_types( + entity_type.BatchDeleteEntityTypesRequest(), + parent='parent_value', + entity_type_names=['entity_type_names_value'], + ) + + +def test_batch_create_entities(transport: str = 'grpc', request_type=entity_type.BatchCreateEntitiesRequest): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_entities), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.batch_create_entities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchCreateEntitiesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_create_entities_from_dict(): + test_batch_create_entities(request_type=dict) + + +def test_batch_create_entities_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_entities), + '__call__') as call: + client.batch_create_entities() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchCreateEntitiesRequest() + + +@pytest.mark.asyncio +async def test_batch_create_entities_async(transport: str = 'grpc_asyncio', request_type=entity_type.BatchCreateEntitiesRequest): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_entities), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.batch_create_entities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchCreateEntitiesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_create_entities_async_from_dict(): + await test_batch_create_entities_async(request_type=dict) + + +def test_batch_create_entities_field_headers(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.BatchCreateEntitiesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_entities), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.batch_create_entities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_batch_create_entities_field_headers_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.BatchCreateEntitiesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_entities), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.batch_create_entities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_batch_create_entities_flattened(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_entities), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_create_entities( + parent='parent_value', + entities=[entity_type.EntityType.Entity(value='value_value')], + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].entities + mock_val = [entity_type.EntityType.Entity(value='value_value')] + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +def test_batch_create_entities_flattened_error(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_create_entities( + entity_type.BatchCreateEntitiesRequest(), + parent='parent_value', + entities=[entity_type.EntityType.Entity(value='value_value')], + language_code='language_code_value', + ) + + +@pytest.mark.asyncio +async def test_batch_create_entities_flattened_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_entities), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_create_entities( + parent='parent_value', + entities=[entity_type.EntityType.Entity(value='value_value')], + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].entities + mock_val = [entity_type.EntityType.Entity(value='value_value')] + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_batch_create_entities_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_create_entities( + entity_type.BatchCreateEntitiesRequest(), + parent='parent_value', + entities=[entity_type.EntityType.Entity(value='value_value')], + language_code='language_code_value', + ) + + +def test_batch_update_entities(transport: str = 'grpc', request_type=entity_type.BatchUpdateEntitiesRequest): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_entities), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.batch_update_entities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchUpdateEntitiesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_update_entities_from_dict(): + test_batch_update_entities(request_type=dict) + + +def test_batch_update_entities_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_entities), + '__call__') as call: + client.batch_update_entities() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchUpdateEntitiesRequest() + + +@pytest.mark.asyncio +async def test_batch_update_entities_async(transport: str = 'grpc_asyncio', request_type=entity_type.BatchUpdateEntitiesRequest): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_entities), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.batch_update_entities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchUpdateEntitiesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_update_entities_async_from_dict(): + await test_batch_update_entities_async(request_type=dict) + + +def test_batch_update_entities_field_headers(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.BatchUpdateEntitiesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_entities), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.batch_update_entities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_batch_update_entities_field_headers_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.BatchUpdateEntitiesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_entities), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.batch_update_entities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_batch_update_entities_flattened(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_entities), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_update_entities( + parent='parent_value', + entities=[entity_type.EntityType.Entity(value='value_value')], + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].entities + mock_val = [entity_type.EntityType.Entity(value='value_value')] + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +def test_batch_update_entities_flattened_error(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_update_entities( + entity_type.BatchUpdateEntitiesRequest(), + parent='parent_value', + entities=[entity_type.EntityType.Entity(value='value_value')], + language_code='language_code_value', + ) + + +@pytest.mark.asyncio +async def test_batch_update_entities_flattened_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_entities), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_update_entities( + parent='parent_value', + entities=[entity_type.EntityType.Entity(value='value_value')], + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].entities + mock_val = [entity_type.EntityType.Entity(value='value_value')] + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_batch_update_entities_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_update_entities( + entity_type.BatchUpdateEntitiesRequest(), + parent='parent_value', + entities=[entity_type.EntityType.Entity(value='value_value')], + language_code='language_code_value', + ) + + +def test_batch_delete_entities(transport: str = 'grpc', request_type=entity_type.BatchDeleteEntitiesRequest): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entities), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.batch_delete_entities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchDeleteEntitiesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_delete_entities_from_dict(): + test_batch_delete_entities(request_type=dict) + + +def test_batch_delete_entities_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entities), + '__call__') as call: + client.batch_delete_entities() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchDeleteEntitiesRequest() + + +@pytest.mark.asyncio +async def test_batch_delete_entities_async(transport: str = 'grpc_asyncio', request_type=entity_type.BatchDeleteEntitiesRequest): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entities), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.batch_delete_entities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.BatchDeleteEntitiesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_delete_entities_async_from_dict(): + await test_batch_delete_entities_async(request_type=dict) + + +def test_batch_delete_entities_field_headers(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.BatchDeleteEntitiesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entities), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.batch_delete_entities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_batch_delete_entities_field_headers_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = entity_type.BatchDeleteEntitiesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entities), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.batch_delete_entities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_batch_delete_entities_flattened(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entities), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_delete_entities( + parent='parent_value', + entity_values=['entity_values_value'], + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].entity_values + mock_val = ['entity_values_value'] + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +def test_batch_delete_entities_flattened_error(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_delete_entities( + entity_type.BatchDeleteEntitiesRequest(), + parent='parent_value', + entity_values=['entity_values_value'], + language_code='language_code_value', + ) + + +@pytest.mark.asyncio +async def test_batch_delete_entities_flattened_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_entities), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_delete_entities( + parent='parent_value', + entity_values=['entity_values_value'], + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].entity_values + mock_val = ['entity_values_value'] + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_batch_delete_entities_flattened_error_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_delete_entities( + entity_type.BatchDeleteEntitiesRequest(), + parent='parent_value', + entity_values=['entity_values_value'], + language_code='language_code_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.EntityTypesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.EntityTypesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EntityTypesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.EntityTypesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EntityTypesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.EntityTypesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = EntityTypesClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.EntityTypesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.EntityTypesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.EntityTypesGrpcTransport, + transports.EntityTypesGrpcAsyncIOTransport, +]) +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 = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.EntityTypesGrpcTransport, + ) + +def test_entity_types_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.EntityTypesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_entity_types_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2beta1.services.entity_types.transports.EntityTypesTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.EntityTypesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_entity_types', + 'get_entity_type', + 'create_entity_type', + 'update_entity_type', + 'delete_entity_type', + 'batch_update_entity_types', + 'batch_delete_entity_types', + 'batch_create_entities', + 'batch_update_entities', + 'batch_delete_entities', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +def test_entity_types_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.dialogflow_v2beta1.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EntityTypesTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_entity_types_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.dialogflow_v2beta1.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EntityTypesTransport() + adc.assert_called_once() + + +def test_entity_types_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) + EntityTypesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EntityTypesGrpcTransport, + transports.EntityTypesGrpcAsyncIOTransport, + ], +) +def test_entity_types_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EntityTypesGrpcTransport, grpc_helpers), + (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_entity_types_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport]) +def test_entity_types_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_entity_types_host_no_port(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_entity_types_host_with_port(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_entity_types_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EntityTypesGrpcTransport( + 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_entity_types_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EntityTypesGrpcAsyncIOTransport( + 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.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport]) +def test_entity_types_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.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport]) +def test_entity_types_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_entity_types_grpc_lro_client(): + client = EntityTypesClient( + 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_entity_types_grpc_lro_async_client(): + client = EntityTypesAsyncClient( + 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_entity_type_path(): + project = "squid" + entity_type = "clam" + expected = "projects/{project}/agent/entityTypes/{entity_type}".format(project=project, entity_type=entity_type, ) + actual = EntityTypesClient.entity_type_path(project, entity_type) + assert expected == actual + + +def test_parse_entity_type_path(): + expected = { + "project": "whelk", + "entity_type": "octopus", + } + path = EntityTypesClient.entity_type_path(**expected) + + # Check that the path construction is reversible. + actual = EntityTypesClient.parse_entity_type_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = EntityTypesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = EntityTypesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = EntityTypesClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = EntityTypesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = EntityTypesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = EntityTypesClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = EntityTypesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = EntityTypesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = EntityTypesClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = EntityTypesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = EntityTypesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = EntityTypesClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = EntityTypesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = EntityTypesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = EntityTypesClient.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.EntityTypesTransport, '_prep_wrapped_messages') as prep: + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.EntityTypesTransport, '_prep_wrapped_messages') as prep: + transport_class = EntityTypesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = EntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = EntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_environments.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_environments.py new file mode 100644 index 000000000..38bd6f4a7 --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_environments.py @@ -0,0 +1,2358 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.environments import EnvironmentsAsyncClient +from google.cloud.dialogflow_v2beta1.services.environments import EnvironmentsClient +from google.cloud.dialogflow_v2beta1.services.environments import pagers +from google.cloud.dialogflow_v2beta1.services.environments import transports +from google.cloud.dialogflow_v2beta1.types import audio_config +from google.cloud.dialogflow_v2beta1.types import environment +from google.cloud.dialogflow_v2beta1.types import fulfillment +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert EnvironmentsClient._get_default_mtls_endpoint(None) is None + assert EnvironmentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert EnvironmentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert EnvironmentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert EnvironmentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert EnvironmentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + EnvironmentsClient, + EnvironmentsAsyncClient, +]) +def test_environments_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.EnvironmentsGrpcTransport, "grpc"), + (transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_environments_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + EnvironmentsClient, + EnvironmentsAsyncClient, +]) +def test_environments_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 == 'dialogflow.googleapis.com:443' + + +def test_environments_client_get_transport_class(): + transport = EnvironmentsClient.get_transport_class() + available_transports = [ + transports.EnvironmentsGrpcTransport, + ] + assert transport in available_transports + + transport = EnvironmentsClient.get_transport_class("grpc") + assert transport == transports.EnvironmentsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(EnvironmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsClient)) +@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsAsyncClient)) +def test_environments_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(EnvironmentsClient, '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(EnvironmentsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", "true"), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", "false"), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(EnvironmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsClient)) +@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_environments_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_environments_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_environments_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_environments_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2beta1.services.environments.transports.EnvironmentsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = EnvironmentsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_environments(transport: str = 'grpc', request_type=environment.ListEnvironmentsRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_environments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.ListEnvironmentsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_environments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.ListEnvironmentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEnvironmentsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_environments_from_dict(): + test_list_environments(request_type=dict) + + +def test_list_environments_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=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_environments), + '__call__') as call: + client.list_environments() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.ListEnvironmentsRequest() + + +@pytest.mark.asyncio +async def test_list_environments_async(transport: str = 'grpc_asyncio', request_type=environment.ListEnvironmentsRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_environments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.ListEnvironmentsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_environments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.ListEnvironmentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEnvironmentsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_environments_async_from_dict(): + await test_list_environments_async(request_type=dict) + + +def test_list_environments_field_headers(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.ListEnvironmentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + call.return_value = environment.ListEnvironmentsResponse() + client.list_environments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_environments_field_headers_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.ListEnvironmentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.ListEnvironmentsResponse()) + await client.list_environments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_environments_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.ListEnvironmentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_environments( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_environments_flattened_error(): + client = EnvironmentsClient( + credentials=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_environments( + environment.ListEnvironmentsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_environments_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.ListEnvironmentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.ListEnvironmentsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_environments( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_environments_flattened_error_async(): + client = EnvironmentsAsyncClient( + credentials=ga_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_environments( + environment.ListEnvironmentsRequest(), + parent='parent_value', + ) + + +def test_list_environments_pager(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.ListEnvironmentsResponse( + environments=[ + environment.Environment(), + environment.Environment(), + environment.Environment(), + ], + next_page_token='abc', + ), + environment.ListEnvironmentsResponse( + environments=[], + next_page_token='def', + ), + environment.ListEnvironmentsResponse( + environments=[ + environment.Environment(), + ], + next_page_token='ghi', + ), + environment.ListEnvironmentsResponse( + environments=[ + environment.Environment(), + environment.Environment(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_environments(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, environment.Environment) + for i in results) + +def test_list_environments_pages(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.ListEnvironmentsResponse( + environments=[ + environment.Environment(), + environment.Environment(), + environment.Environment(), + ], + next_page_token='abc', + ), + environment.ListEnvironmentsResponse( + environments=[], + next_page_token='def', + ), + environment.ListEnvironmentsResponse( + environments=[ + environment.Environment(), + ], + next_page_token='ghi', + ), + environment.ListEnvironmentsResponse( + environments=[ + environment.Environment(), + environment.Environment(), + ], + ), + RuntimeError, + ) + pages = list(client.list_environments(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_environments_async_pager(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.ListEnvironmentsResponse( + environments=[ + environment.Environment(), + environment.Environment(), + environment.Environment(), + ], + next_page_token='abc', + ), + environment.ListEnvironmentsResponse( + environments=[], + next_page_token='def', + ), + environment.ListEnvironmentsResponse( + environments=[ + environment.Environment(), + ], + next_page_token='ghi', + ), + environment.ListEnvironmentsResponse( + environments=[ + environment.Environment(), + environment.Environment(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_environments(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, environment.Environment) + for i in responses) + +@pytest.mark.asyncio +async def test_list_environments_async_pages(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.ListEnvironmentsResponse( + environments=[ + environment.Environment(), + environment.Environment(), + environment.Environment(), + ], + next_page_token='abc', + ), + environment.ListEnvironmentsResponse( + environments=[], + next_page_token='def', + ), + environment.ListEnvironmentsResponse( + environments=[ + environment.Environment(), + ], + next_page_token='ghi', + ), + environment.ListEnvironmentsResponse( + environments=[ + environment.Environment(), + environment.Environment(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_environments(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_environment(transport: str = 'grpc', request_type=environment.GetEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.Environment( + name='name_value', + description='description_value', + agent_version='agent_version_value', + state=environment.Environment.State.STOPPED, + ) + response = client.get_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.agent_version == 'agent_version_value' + assert response.state == environment.Environment.State.STOPPED + + +def test_get_environment_from_dict(): + test_get_environment(request_type=dict) + + +def test_get_environment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=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_environment), + '__call__') as call: + client.get_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_get_environment_async(transport: str = 'grpc_asyncio', request_type=environment.GetEnvironmentRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment( + name='name_value', + description='description_value', + agent_version='agent_version_value', + state=environment.Environment.State.STOPPED, + )) + response = await client.get_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.agent_version == 'agent_version_value' + assert response.state == environment.Environment.State.STOPPED + + +@pytest.mark.asyncio +async def test_get_environment_async_from_dict(): + await test_get_environment_async(request_type=dict) + + +def test_get_environment_field_headers(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.GetEnvironmentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment), + '__call__') as call: + call.return_value = environment.Environment() + client.get_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_environment_field_headers_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.GetEnvironmentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment()) + await client.get_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_create_environment(transport: str = 'grpc', request_type=environment.CreateEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.Environment( + name='name_value', + description='description_value', + agent_version='agent_version_value', + state=environment.Environment.State.STOPPED, + ) + response = client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.CreateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.agent_version == 'agent_version_value' + assert response.state == environment.Environment.State.STOPPED + + +def test_create_environment_from_dict(): + test_create_environment(request_type=dict) + + +def test_create_environment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=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_environment), + '__call__') as call: + client.create_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.CreateEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_create_environment_async(transport: str = 'grpc_asyncio', request_type=environment.CreateEnvironmentRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment( + name='name_value', + description='description_value', + agent_version='agent_version_value', + state=environment.Environment.State.STOPPED, + )) + response = await client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.CreateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.agent_version == 'agent_version_value' + assert response.state == environment.Environment.State.STOPPED + + +@pytest.mark.asyncio +async def test_create_environment_async_from_dict(): + await test_create_environment_async(request_type=dict) + + +def test_create_environment_field_headers(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.CreateEnvironmentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__call__') as call: + call.return_value = environment.Environment() + client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_environment_field_headers_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.CreateEnvironmentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment()) + await client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_update_environment(transport: str = 'grpc', request_type=environment.UpdateEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.Environment( + name='name_value', + description='description_value', + agent_version='agent_version_value', + state=environment.Environment.State.STOPPED, + ) + response = client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.UpdateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.agent_version == 'agent_version_value' + assert response.state == environment.Environment.State.STOPPED + + +def test_update_environment_from_dict(): + test_update_environment(request_type=dict) + + +def test_update_environment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=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_environment), + '__call__') as call: + client.update_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.UpdateEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_update_environment_async(transport: str = 'grpc_asyncio', request_type=environment.UpdateEnvironmentRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment( + name='name_value', + description='description_value', + agent_version='agent_version_value', + state=environment.Environment.State.STOPPED, + )) + response = await client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.UpdateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.agent_version == 'agent_version_value' + assert response.state == environment.Environment.State.STOPPED + + +@pytest.mark.asyncio +async def test_update_environment_async_from_dict(): + await test_update_environment_async(request_type=dict) + + +def test_update_environment_field_headers(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.UpdateEnvironmentRequest() + + request.environment.name = 'environment.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__call__') as call: + call.return_value = environment.Environment() + client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'environment.name=environment.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_environment_field_headers_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.UpdateEnvironmentRequest() + + request.environment.name = 'environment.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment()) + await client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'environment.name=environment.name/value', + ) in kw['metadata'] + + +def test_delete_environment(transport: str = 'grpc', request_type=environment.DeleteEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.DeleteEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_environment_from_dict(): + test_delete_environment(request_type=dict) + + +def test_delete_environment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=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_environment), + '__call__') as call: + client.delete_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.DeleteEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_delete_environment_async(transport: str = 'grpc_asyncio', request_type=environment.DeleteEnvironmentRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.DeleteEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_environment_async_from_dict(): + await test_delete_environment_async(request_type=dict) + + +def test_delete_environment_field_headers(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.DeleteEnvironmentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__call__') as call: + call.return_value = None + client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_environment_field_headers_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.DeleteEnvironmentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_environment_history(transport: str = 'grpc', request_type=environment.GetEnvironmentHistoryRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_environment_history), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.EnvironmentHistory( + parent='parent_value', + next_page_token='next_page_token_value', + ) + response = client.get_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentHistoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GetEnvironmentHistoryPager) + assert response.parent == 'parent_value' + assert response.next_page_token == 'next_page_token_value' + + +def test_get_environment_history_from_dict(): + test_get_environment_history(request_type=dict) + + +def test_get_environment_history_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=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_environment_history), + '__call__') as call: + client.get_environment_history() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentHistoryRequest() + + +@pytest.mark.asyncio +async def test_get_environment_history_async(transport: str = 'grpc_asyncio', request_type=environment.GetEnvironmentHistoryRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_environment_history), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.EnvironmentHistory( + parent='parent_value', + next_page_token='next_page_token_value', + )) + response = await client.get_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentHistoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GetEnvironmentHistoryAsyncPager) + assert response.parent == 'parent_value' + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_get_environment_history_async_from_dict(): + await test_get_environment_history_async(request_type=dict) + + +def test_get_environment_history_field_headers(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.GetEnvironmentHistoryRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__') as call: + call.return_value = environment.EnvironmentHistory() + client.get_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_get_environment_history_field_headers_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.GetEnvironmentHistoryRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.EnvironmentHistory()) + await client.get_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_get_environment_history_pager(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token='abc', + ), + environment.EnvironmentHistory( + entries=[], + next_page_token='def', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + ], + next_page_token='ghi', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.get_environment_history(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, environment.EnvironmentHistory.Entry) + for i in results) + +def test_get_environment_history_pages(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token='abc', + ), + environment.EnvironmentHistory( + entries=[], + next_page_token='def', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + ], + next_page_token='ghi', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + pages = list(client.get_environment_history(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_get_environment_history_async_pager(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token='abc', + ), + environment.EnvironmentHistory( + entries=[], + next_page_token='def', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + ], + next_page_token='ghi', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + async_pager = await client.get_environment_history(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, environment.EnvironmentHistory.Entry) + for i in responses) + +@pytest.mark.asyncio +async def test_get_environment_history_async_pages(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token='abc', + ), + environment.EnvironmentHistory( + entries=[], + next_page_token='def', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + ], + next_page_token='ghi', + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.get_environment_history(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.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = EnvironmentsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.EnvironmentsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.EnvironmentsGrpcTransport, + transports.EnvironmentsGrpcAsyncIOTransport, +]) +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 = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.EnvironmentsGrpcTransport, + ) + +def test_environments_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.EnvironmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_environments_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2beta1.services.environments.transports.EnvironmentsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.EnvironmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_environments', + 'get_environment', + 'create_environment', + 'update_environment', + 'delete_environment', + 'get_environment_history', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_environments_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.dialogflow_v2beta1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EnvironmentsTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_environments_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.dialogflow_v2beta1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EnvironmentsTransport() + adc.assert_called_once() + + +def test_environments_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) + EnvironmentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EnvironmentsGrpcTransport, + transports.EnvironmentsGrpcAsyncIOTransport, + ], +) +def test_environments_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EnvironmentsGrpcTransport, grpc_helpers), + (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_environments_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport]) +def test_environments_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_environments_host_no_port(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_environments_host_with_port(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_environments_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EnvironmentsGrpcTransport( + 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_environments_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EnvironmentsGrpcAsyncIOTransport( + 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.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport]) +def test_environments_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.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport]) +def test_environments_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_environment_path(): + project = "squid" + environment = "clam" + expected = "projects/{project}/agent/environments/{environment}".format(project=project, environment=environment, ) + actual = EnvironmentsClient.environment_path(project, environment) + assert expected == actual + + +def test_parse_environment_path(): + expected = { + "project": "whelk", + "environment": "octopus", + } + path = EnvironmentsClient.environment_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_environment_path(path) + assert expected == actual + +def test_fulfillment_path(): + project = "oyster" + expected = "projects/{project}/agent/fulfillment".format(project=project, ) + actual = EnvironmentsClient.fulfillment_path(project) + assert expected == actual + + +def test_parse_fulfillment_path(): + expected = { + "project": "nudibranch", + } + path = EnvironmentsClient.fulfillment_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_fulfillment_path(path) + assert expected == actual + +def test_version_path(): + project = "cuttlefish" + version = "mussel" + expected = "projects/{project}/agent/versions/{version}".format(project=project, version=version, ) + actual = EnvironmentsClient.version_path(project, version) + assert expected == actual + + +def test_parse_version_path(): + expected = { + "project": "winkle", + "version": "nautilus", + } + path = EnvironmentsClient.version_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_version_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = EnvironmentsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = EnvironmentsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = EnvironmentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = EnvironmentsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = EnvironmentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = EnvironmentsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = EnvironmentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = EnvironmentsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.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 = EnvironmentsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = EnvironmentsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.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.EnvironmentsTransport, '_prep_wrapped_messages') as prep: + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.EnvironmentsTransport, '_prep_wrapped_messages') as prep: + transport_class = EnvironmentsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_fulfillments.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_fulfillments.py new file mode 100644 index 000000000..aa11964d0 --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_fulfillments.py @@ -0,0 +1,1414 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.fulfillments import FulfillmentsAsyncClient +from google.cloud.dialogflow_v2beta1.services.fulfillments import FulfillmentsClient +from google.cloud.dialogflow_v2beta1.services.fulfillments import transports +from google.cloud.dialogflow_v2beta1.types import fulfillment +from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert FulfillmentsClient._get_default_mtls_endpoint(None) is None + assert FulfillmentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert FulfillmentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert FulfillmentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert FulfillmentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert FulfillmentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + FulfillmentsClient, + FulfillmentsAsyncClient, +]) +def test_fulfillments_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.FulfillmentsGrpcTransport, "grpc"), + (transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_fulfillments_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + FulfillmentsClient, + FulfillmentsAsyncClient, +]) +def test_fulfillments_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 == 'dialogflow.googleapis.com:443' + + +def test_fulfillments_client_get_transport_class(): + transport = FulfillmentsClient.get_transport_class() + available_transports = [ + transports.FulfillmentsGrpcTransport, + ] + assert transport in available_transports + + transport = FulfillmentsClient.get_transport_class("grpc") + assert transport == transports.FulfillmentsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), + (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(FulfillmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsClient)) +@mock.patch.object(FulfillmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsAsyncClient)) +def test_fulfillments_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(FulfillmentsClient, '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(FulfillmentsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc", "true"), + (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc", "false"), + (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(FulfillmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsClient)) +@mock.patch.object(FulfillmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_fulfillments_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), + (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_fulfillments_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), + (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_fulfillments_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_fulfillments_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2beta1.services.fulfillments.transports.FulfillmentsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = FulfillmentsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_get_fulfillment(transport: str = 'grpc', request_type=fulfillment.GetFulfillmentRequest): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = fulfillment.Fulfillment( + name='name_value', + display_name='display_name_value', + enabled=True, + generic_web_service=fulfillment.Fulfillment.GenericWebService(uri='uri_value'), + ) + response = client.get_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == fulfillment.GetFulfillmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, fulfillment.Fulfillment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enabled is True + + +def test_get_fulfillment_from_dict(): + test_get_fulfillment(request_type=dict) + + +def test_get_fulfillment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FulfillmentsClient( + credentials=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_fulfillment), + '__call__') as call: + client.get_fulfillment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == fulfillment.GetFulfillmentRequest() + + +@pytest.mark.asyncio +async def test_get_fulfillment_async(transport: str = 'grpc_asyncio', request_type=fulfillment.GetFulfillmentRequest): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(fulfillment.Fulfillment( + name='name_value', + display_name='display_name_value', + enabled=True, + )) + response = await client.get_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == fulfillment.GetFulfillmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, fulfillment.Fulfillment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enabled is True + + +@pytest.mark.asyncio +async def test_get_fulfillment_async_from_dict(): + await test_get_fulfillment_async(request_type=dict) + + +def test_get_fulfillment_field_headers(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = fulfillment.GetFulfillmentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_fulfillment), + '__call__') as call: + call.return_value = fulfillment.Fulfillment() + client.get_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_fulfillment_field_headers_async(): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = fulfillment.GetFulfillmentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_fulfillment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(fulfillment.Fulfillment()) + await client.get_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_fulfillment_flattened(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = fulfillment.Fulfillment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_fulfillment( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_fulfillment_flattened_error(): + client = FulfillmentsClient( + credentials=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_fulfillment( + fulfillment.GetFulfillmentRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_fulfillment_flattened_async(): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = fulfillment.Fulfillment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(fulfillment.Fulfillment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_fulfillment( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_fulfillment_flattened_error_async(): + client = FulfillmentsAsyncClient( + credentials=ga_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_fulfillment( + fulfillment.GetFulfillmentRequest(), + name='name_value', + ) + + +def test_update_fulfillment(transport: str = 'grpc', request_type=gcd_fulfillment.UpdateFulfillmentRequest): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_fulfillment.Fulfillment( + name='name_value', + display_name='display_name_value', + enabled=True, + generic_web_service=gcd_fulfillment.Fulfillment.GenericWebService(uri='uri_value'), + ) + response = client.update_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_fulfillment.UpdateFulfillmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_fulfillment.Fulfillment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enabled is True + + +def test_update_fulfillment_from_dict(): + test_update_fulfillment(request_type=dict) + + +def test_update_fulfillment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FulfillmentsClient( + credentials=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_fulfillment), + '__call__') as call: + client.update_fulfillment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_fulfillment.UpdateFulfillmentRequest() + + +@pytest.mark.asyncio +async def test_update_fulfillment_async(transport: str = 'grpc_asyncio', request_type=gcd_fulfillment.UpdateFulfillmentRequest): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_fulfillment.Fulfillment( + name='name_value', + display_name='display_name_value', + enabled=True, + )) + response = await client.update_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_fulfillment.UpdateFulfillmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_fulfillment.Fulfillment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enabled is True + + +@pytest.mark.asyncio +async def test_update_fulfillment_async_from_dict(): + await test_update_fulfillment_async(request_type=dict) + + +def test_update_fulfillment_field_headers(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_fulfillment.UpdateFulfillmentRequest() + + request.fulfillment.name = 'fulfillment.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), + '__call__') as call: + call.return_value = gcd_fulfillment.Fulfillment() + client.update_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'fulfillment.name=fulfillment.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_fulfillment_field_headers_async(): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_fulfillment.UpdateFulfillmentRequest() + + request.fulfillment.name = 'fulfillment.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_fulfillment.Fulfillment()) + await client.update_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'fulfillment.name=fulfillment.name/value', + ) in kw['metadata'] + + +def test_update_fulfillment_flattened(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_fulfillment.Fulfillment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_fulfillment( + fulfillment=gcd_fulfillment.Fulfillment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].fulfillment + mock_val = gcd_fulfillment.Fulfillment(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_fulfillment_flattened_error(): + client = FulfillmentsClient( + credentials=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_fulfillment( + gcd_fulfillment.UpdateFulfillmentRequest(), + fulfillment=gcd_fulfillment.Fulfillment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_fulfillment_flattened_async(): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_fulfillment.Fulfillment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_fulfillment.Fulfillment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_fulfillment( + fulfillment=gcd_fulfillment.Fulfillment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].fulfillment + mock_val = gcd_fulfillment.Fulfillment(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_fulfillment_flattened_error_async(): + client = FulfillmentsAsyncClient( + credentials=ga_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_fulfillment( + gcd_fulfillment.UpdateFulfillmentRequest(), + fulfillment=gcd_fulfillment.Fulfillment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FulfillmentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FulfillmentsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = FulfillmentsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.FulfillmentsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.FulfillmentsGrpcTransport, + transports.FulfillmentsGrpcAsyncIOTransport, +]) +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 = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.FulfillmentsGrpcTransport, + ) + +def test_fulfillments_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.FulfillmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_fulfillments_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2beta1.services.fulfillments.transports.FulfillmentsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.FulfillmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_fulfillment', + 'update_fulfillment', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_fulfillments_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.dialogflow_v2beta1.services.fulfillments.transports.FulfillmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FulfillmentsTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_fulfillments_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.dialogflow_v2beta1.services.fulfillments.transports.FulfillmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FulfillmentsTransport() + adc.assert_called_once() + + +def test_fulfillments_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) + FulfillmentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FulfillmentsGrpcTransport, + transports.FulfillmentsGrpcAsyncIOTransport, + ], +) +def test_fulfillments_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FulfillmentsGrpcTransport, grpc_helpers), + (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_fulfillments_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.FulfillmentsGrpcTransport, transports.FulfillmentsGrpcAsyncIOTransport]) +def test_fulfillments_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_fulfillments_host_no_port(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_fulfillments_host_with_port(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_fulfillments_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FulfillmentsGrpcTransport( + 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_fulfillments_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FulfillmentsGrpcAsyncIOTransport( + 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.FulfillmentsGrpcTransport, transports.FulfillmentsGrpcAsyncIOTransport]) +def test_fulfillments_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.FulfillmentsGrpcTransport, transports.FulfillmentsGrpcAsyncIOTransport]) +def test_fulfillments_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_fulfillment_path(): + project = "squid" + expected = "projects/{project}/agent/fulfillment".format(project=project, ) + actual = FulfillmentsClient.fulfillment_path(project) + assert expected == actual + + +def test_parse_fulfillment_path(): + expected = { + "project": "clam", + } + path = FulfillmentsClient.fulfillment_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_fulfillment_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = FulfillmentsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = FulfillmentsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = FulfillmentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = FulfillmentsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = FulfillmentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = FulfillmentsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = FulfillmentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = FulfillmentsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = FulfillmentsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = FulfillmentsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.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.FulfillmentsTransport, '_prep_wrapped_messages') as prep: + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.FulfillmentsTransport, '_prep_wrapped_messages') as prep: + transport_class = FulfillmentsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_intents.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_intents.py new file mode 100644 index 000000000..8f4a029ff --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_intents.py @@ -0,0 +1,3071 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.intents import IntentsAsyncClient +from google.cloud.dialogflow_v2beta1.services.intents import IntentsClient +from google.cloud.dialogflow_v2beta1.services.intents import pagers +from google.cloud.dialogflow_v2beta1.services.intents import transports +from google.cloud.dialogflow_v2beta1.types import context +from google.cloud.dialogflow_v2beta1.types import intent +from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent +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 struct_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert IntentsClient._get_default_mtls_endpoint(None) is None + assert IntentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert IntentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert IntentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert IntentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert IntentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + IntentsClient, + IntentsAsyncClient, +]) +def test_intents_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.IntentsGrpcTransport, "grpc"), + (transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_intents_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + IntentsClient, + IntentsAsyncClient, +]) +def test_intents_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 == 'dialogflow.googleapis.com:443' + + +def test_intents_client_get_transport_class(): + transport = IntentsClient.get_transport_class() + available_transports = [ + transports.IntentsGrpcTransport, + ] + assert transport in available_transports + + transport = IntentsClient.get_transport_class("grpc") + assert transport == transports.IntentsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (IntentsClient, transports.IntentsGrpcTransport, "grpc"), + (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(IntentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IntentsClient)) +@mock.patch.object(IntentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IntentsAsyncClient)) +def test_intents_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(IntentsClient, '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(IntentsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (IntentsClient, transports.IntentsGrpcTransport, "grpc", "true"), + (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (IntentsClient, transports.IntentsGrpcTransport, "grpc", "false"), + (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(IntentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IntentsClient)) +@mock.patch.object(IntentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IntentsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_intents_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (IntentsClient, transports.IntentsGrpcTransport, "grpc"), + (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_intents_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (IntentsClient, transports.IntentsGrpcTransport, "grpc"), + (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_intents_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_intents_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2beta1.services.intents.transports.IntentsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = IntentsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_intents(transport: str = 'grpc', request_type=intent.ListIntentsRequest): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_intents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = intent.ListIntentsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_intents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == intent.ListIntentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListIntentsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_intents_from_dict(): + test_list_intents(request_type=dict) + + +def test_list_intents_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IntentsClient( + credentials=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_intents), + '__call__') as call: + client.list_intents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == intent.ListIntentsRequest() + + +@pytest.mark.asyncio +async def test_list_intents_async(transport: str = 'grpc_asyncio', request_type=intent.ListIntentsRequest): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_intents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(intent.ListIntentsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_intents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == intent.ListIntentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListIntentsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_intents_async_from_dict(): + await test_list_intents_async(request_type=dict) + + +def test_list_intents_field_headers(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = intent.ListIntentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intents), + '__call__') as call: + call.return_value = intent.ListIntentsResponse() + client.list_intents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_intents_field_headers_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = intent.ListIntentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(intent.ListIntentsResponse()) + await client.list_intents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_intents_flattened(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = intent.ListIntentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_intents( + parent='parent_value', + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +def test_list_intents_flattened_error(): + client = IntentsClient( + credentials=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_intents( + intent.ListIntentsRequest(), + parent='parent_value', + language_code='language_code_value', + ) + + +@pytest.mark.asyncio +async def test_list_intents_flattened_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = intent.ListIntentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(intent.ListIntentsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_intents( + parent='parent_value', + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_intents_flattened_error_async(): + client = IntentsAsyncClient( + credentials=ga_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_intents( + intent.ListIntentsRequest(), + parent='parent_value', + language_code='language_code_value', + ) + + +def test_list_intents_pager(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intents), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + intent.ListIntentsResponse( + intents=[ + intent.Intent(), + intent.Intent(), + intent.Intent(), + ], + next_page_token='abc', + ), + intent.ListIntentsResponse( + intents=[], + next_page_token='def', + ), + intent.ListIntentsResponse( + intents=[ + intent.Intent(), + ], + next_page_token='ghi', + ), + intent.ListIntentsResponse( + intents=[ + intent.Intent(), + intent.Intent(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_intents(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, intent.Intent) + for i in results) + +def test_list_intents_pages(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intents), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + intent.ListIntentsResponse( + intents=[ + intent.Intent(), + intent.Intent(), + intent.Intent(), + ], + next_page_token='abc', + ), + intent.ListIntentsResponse( + intents=[], + next_page_token='def', + ), + intent.ListIntentsResponse( + intents=[ + intent.Intent(), + ], + next_page_token='ghi', + ), + intent.ListIntentsResponse( + intents=[ + intent.Intent(), + intent.Intent(), + ], + ), + RuntimeError, + ) + pages = list(client.list_intents(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_intents_async_pager(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intents), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + intent.ListIntentsResponse( + intents=[ + intent.Intent(), + intent.Intent(), + intent.Intent(), + ], + next_page_token='abc', + ), + intent.ListIntentsResponse( + intents=[], + next_page_token='def', + ), + intent.ListIntentsResponse( + intents=[ + intent.Intent(), + ], + next_page_token='ghi', + ), + intent.ListIntentsResponse( + intents=[ + intent.Intent(), + intent.Intent(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_intents(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, intent.Intent) + for i in responses) + +@pytest.mark.asyncio +async def test_list_intents_async_pages(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intents), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + intent.ListIntentsResponse( + intents=[ + intent.Intent(), + intent.Intent(), + intent.Intent(), + ], + next_page_token='abc', + ), + intent.ListIntentsResponse( + intents=[], + next_page_token='def', + ), + intent.ListIntentsResponse( + intents=[ + intent.Intent(), + ], + next_page_token='ghi', + ), + intent.ListIntentsResponse( + intents=[ + intent.Intent(), + intent.Intent(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_intents(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_intent(transport: str = 'grpc', request_type=intent.GetIntentRequest): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = intent.Intent( + name='name_value', + display_name='display_name_value', + webhook_state=intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, + priority=898, + is_fallback=True, + ml_enabled=True, + ml_disabled=True, + live_agent_handoff=True, + end_interaction=True, + input_context_names=['input_context_names_value'], + events=['events_value'], + action='action_value', + reset_contexts=True, + default_response_platforms=[intent.Intent.Message.Platform.FACEBOOK], + root_followup_intent_name='root_followup_intent_name_value', + parent_followup_intent_name='parent_followup_intent_name_value', + ) + response = client.get_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == intent.GetIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, intent.Intent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.webhook_state == intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED + assert response.priority == 898 + assert response.is_fallback is True + assert response.ml_enabled is True + assert response.ml_disabled is True + assert response.live_agent_handoff is True + assert response.end_interaction is True + assert response.input_context_names == ['input_context_names_value'] + assert response.events == ['events_value'] + assert response.action == 'action_value' + assert response.reset_contexts is True + assert response.default_response_platforms == [intent.Intent.Message.Platform.FACEBOOK] + assert response.root_followup_intent_name == 'root_followup_intent_name_value' + assert response.parent_followup_intent_name == 'parent_followup_intent_name_value' + + +def test_get_intent_from_dict(): + test_get_intent(request_type=dict) + + +def test_get_intent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IntentsClient( + credentials=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_intent), + '__call__') as call: + client.get_intent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == intent.GetIntentRequest() + + +@pytest.mark.asyncio +async def test_get_intent_async(transport: str = 'grpc_asyncio', request_type=intent.GetIntentRequest): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(intent.Intent( + name='name_value', + display_name='display_name_value', + webhook_state=intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, + priority=898, + is_fallback=True, + ml_enabled=True, + ml_disabled=True, + live_agent_handoff=True, + end_interaction=True, + input_context_names=['input_context_names_value'], + events=['events_value'], + action='action_value', + reset_contexts=True, + default_response_platforms=[intent.Intent.Message.Platform.FACEBOOK], + root_followup_intent_name='root_followup_intent_name_value', + parent_followup_intent_name='parent_followup_intent_name_value', + )) + response = await client.get_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == intent.GetIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, intent.Intent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.webhook_state == intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED + assert response.priority == 898 + assert response.is_fallback is True + assert response.ml_enabled is True + assert response.ml_disabled is True + assert response.live_agent_handoff is True + assert response.end_interaction is True + assert response.input_context_names == ['input_context_names_value'] + assert response.events == ['events_value'] + assert response.action == 'action_value' + assert response.reset_contexts is True + assert response.default_response_platforms == [intent.Intent.Message.Platform.FACEBOOK] + assert response.root_followup_intent_name == 'root_followup_intent_name_value' + assert response.parent_followup_intent_name == 'parent_followup_intent_name_value' + + +@pytest.mark.asyncio +async def test_get_intent_async_from_dict(): + await test_get_intent_async(request_type=dict) + + +def test_get_intent_field_headers(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = intent.GetIntentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_intent), + '__call__') as call: + call.return_value = intent.Intent() + client.get_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_intent_field_headers_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = intent.GetIntentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_intent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(intent.Intent()) + await client.get_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_intent_flattened(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = intent.Intent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_intent( + name='name_value', + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +def test_get_intent_flattened_error(): + client = IntentsClient( + credentials=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_intent( + intent.GetIntentRequest(), + name='name_value', + language_code='language_code_value', + ) + + +@pytest.mark.asyncio +async def test_get_intent_flattened_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = intent.Intent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(intent.Intent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_intent( + name='name_value', + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_intent_flattened_error_async(): + client = IntentsAsyncClient( + credentials=ga_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_intent( + intent.GetIntentRequest(), + name='name_value', + language_code='language_code_value', + ) + + +def test_create_intent(transport: str = 'grpc', request_type=gcd_intent.CreateIntentRequest): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_intent.Intent( + name='name_value', + display_name='display_name_value', + webhook_state=gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, + priority=898, + is_fallback=True, + ml_enabled=True, + ml_disabled=True, + live_agent_handoff=True, + end_interaction=True, + input_context_names=['input_context_names_value'], + events=['events_value'], + action='action_value', + reset_contexts=True, + default_response_platforms=[gcd_intent.Intent.Message.Platform.FACEBOOK], + root_followup_intent_name='root_followup_intent_name_value', + parent_followup_intent_name='parent_followup_intent_name_value', + ) + response = client.create_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_intent.CreateIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_intent.Intent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.webhook_state == gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED + assert response.priority == 898 + assert response.is_fallback is True + assert response.ml_enabled is True + assert response.ml_disabled is True + assert response.live_agent_handoff is True + assert response.end_interaction is True + assert response.input_context_names == ['input_context_names_value'] + assert response.events == ['events_value'] + assert response.action == 'action_value' + assert response.reset_contexts is True + assert response.default_response_platforms == [gcd_intent.Intent.Message.Platform.FACEBOOK] + assert response.root_followup_intent_name == 'root_followup_intent_name_value' + assert response.parent_followup_intent_name == 'parent_followup_intent_name_value' + + +def test_create_intent_from_dict(): + test_create_intent(request_type=dict) + + +def test_create_intent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IntentsClient( + credentials=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_intent), + '__call__') as call: + client.create_intent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_intent.CreateIntentRequest() + + +@pytest.mark.asyncio +async def test_create_intent_async(transport: str = 'grpc_asyncio', request_type=gcd_intent.CreateIntentRequest): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent( + name='name_value', + display_name='display_name_value', + webhook_state=gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, + priority=898, + is_fallback=True, + ml_enabled=True, + ml_disabled=True, + live_agent_handoff=True, + end_interaction=True, + input_context_names=['input_context_names_value'], + events=['events_value'], + action='action_value', + reset_contexts=True, + default_response_platforms=[gcd_intent.Intent.Message.Platform.FACEBOOK], + root_followup_intent_name='root_followup_intent_name_value', + parent_followup_intent_name='parent_followup_intent_name_value', + )) + response = await client.create_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_intent.CreateIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_intent.Intent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.webhook_state == gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED + assert response.priority == 898 + assert response.is_fallback is True + assert response.ml_enabled is True + assert response.ml_disabled is True + assert response.live_agent_handoff is True + assert response.end_interaction is True + assert response.input_context_names == ['input_context_names_value'] + assert response.events == ['events_value'] + assert response.action == 'action_value' + assert response.reset_contexts is True + assert response.default_response_platforms == [gcd_intent.Intent.Message.Platform.FACEBOOK] + assert response.root_followup_intent_name == 'root_followup_intent_name_value' + assert response.parent_followup_intent_name == 'parent_followup_intent_name_value' + + +@pytest.mark.asyncio +async def test_create_intent_async_from_dict(): + await test_create_intent_async(request_type=dict) + + +def test_create_intent_field_headers(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_intent.CreateIntentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_intent), + '__call__') as call: + call.return_value = gcd_intent.Intent() + client.create_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_intent_field_headers_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_intent.CreateIntentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_intent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent()) + await client.create_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_intent_flattened(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_intent.Intent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_intent( + parent='parent_value', + intent=gcd_intent.Intent(name='name_value'), + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].intent + mock_val = gcd_intent.Intent(name='name_value') + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +def test_create_intent_flattened_error(): + client = IntentsClient( + credentials=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_intent( + gcd_intent.CreateIntentRequest(), + parent='parent_value', + intent=gcd_intent.Intent(name='name_value'), + language_code='language_code_value', + ) + + +@pytest.mark.asyncio +async def test_create_intent_flattened_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_intent.Intent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_intent( + parent='parent_value', + intent=gcd_intent.Intent(name='name_value'), + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].intent + mock_val = gcd_intent.Intent(name='name_value') + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_intent_flattened_error_async(): + client = IntentsAsyncClient( + credentials=ga_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_intent( + gcd_intent.CreateIntentRequest(), + parent='parent_value', + intent=gcd_intent.Intent(name='name_value'), + language_code='language_code_value', + ) + + +def test_update_intent(transport: str = 'grpc', request_type=gcd_intent.UpdateIntentRequest): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_intent.Intent( + name='name_value', + display_name='display_name_value', + webhook_state=gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, + priority=898, + is_fallback=True, + ml_enabled=True, + ml_disabled=True, + live_agent_handoff=True, + end_interaction=True, + input_context_names=['input_context_names_value'], + events=['events_value'], + action='action_value', + reset_contexts=True, + default_response_platforms=[gcd_intent.Intent.Message.Platform.FACEBOOK], + root_followup_intent_name='root_followup_intent_name_value', + parent_followup_intent_name='parent_followup_intent_name_value', + ) + response = client.update_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_intent.UpdateIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_intent.Intent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.webhook_state == gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED + assert response.priority == 898 + assert response.is_fallback is True + assert response.ml_enabled is True + assert response.ml_disabled is True + assert response.live_agent_handoff is True + assert response.end_interaction is True + assert response.input_context_names == ['input_context_names_value'] + assert response.events == ['events_value'] + assert response.action == 'action_value' + assert response.reset_contexts is True + assert response.default_response_platforms == [gcd_intent.Intent.Message.Platform.FACEBOOK] + assert response.root_followup_intent_name == 'root_followup_intent_name_value' + assert response.parent_followup_intent_name == 'parent_followup_intent_name_value' + + +def test_update_intent_from_dict(): + test_update_intent(request_type=dict) + + +def test_update_intent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IntentsClient( + credentials=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_intent), + '__call__') as call: + client.update_intent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_intent.UpdateIntentRequest() + + +@pytest.mark.asyncio +async def test_update_intent_async(transport: str = 'grpc_asyncio', request_type=gcd_intent.UpdateIntentRequest): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent( + name='name_value', + display_name='display_name_value', + webhook_state=gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, + priority=898, + is_fallback=True, + ml_enabled=True, + ml_disabled=True, + live_agent_handoff=True, + end_interaction=True, + input_context_names=['input_context_names_value'], + events=['events_value'], + action='action_value', + reset_contexts=True, + default_response_platforms=[gcd_intent.Intent.Message.Platform.FACEBOOK], + root_followup_intent_name='root_followup_intent_name_value', + parent_followup_intent_name='parent_followup_intent_name_value', + )) + response = await client.update_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_intent.UpdateIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_intent.Intent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.webhook_state == gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED + assert response.priority == 898 + assert response.is_fallback is True + assert response.ml_enabled is True + assert response.ml_disabled is True + assert response.live_agent_handoff is True + assert response.end_interaction is True + assert response.input_context_names == ['input_context_names_value'] + assert response.events == ['events_value'] + assert response.action == 'action_value' + assert response.reset_contexts is True + assert response.default_response_platforms == [gcd_intent.Intent.Message.Platform.FACEBOOK] + assert response.root_followup_intent_name == 'root_followup_intent_name_value' + assert response.parent_followup_intent_name == 'parent_followup_intent_name_value' + + +@pytest.mark.asyncio +async def test_update_intent_async_from_dict(): + await test_update_intent_async(request_type=dict) + + +def test_update_intent_field_headers(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_intent.UpdateIntentRequest() + + request.intent.name = 'intent.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_intent), + '__call__') as call: + call.return_value = gcd_intent.Intent() + client.update_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'intent.name=intent.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_intent_field_headers_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_intent.UpdateIntentRequest() + + request.intent.name = 'intent.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_intent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent()) + await client.update_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'intent.name=intent.name/value', + ) in kw['metadata'] + + +def test_update_intent_flattened(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_intent.Intent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_intent( + intent=gcd_intent.Intent(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].intent + mock_val = gcd_intent.Intent(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +def test_update_intent_flattened_error(): + client = IntentsClient( + credentials=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_intent( + gcd_intent.UpdateIntentRequest(), + intent=gcd_intent.Intent(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + language_code='language_code_value', + ) + + +@pytest.mark.asyncio +async def test_update_intent_flattened_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_intent.Intent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_intent( + intent=gcd_intent.Intent(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + language_code='language_code_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].intent + mock_val = gcd_intent.Intent(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + arg = args[0].language_code + mock_val = 'language_code_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_intent_flattened_error_async(): + client = IntentsAsyncClient( + credentials=ga_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_intent( + gcd_intent.UpdateIntentRequest(), + intent=gcd_intent.Intent(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + language_code='language_code_value', + ) + + +def test_delete_intent(transport: str = 'grpc', request_type=intent.DeleteIntentRequest): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == intent.DeleteIntentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_intent_from_dict(): + test_delete_intent(request_type=dict) + + +def test_delete_intent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IntentsClient( + credentials=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_intent), + '__call__') as call: + client.delete_intent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == intent.DeleteIntentRequest() + + +@pytest.mark.asyncio +async def test_delete_intent_async(transport: str = 'grpc_asyncio', request_type=intent.DeleteIntentRequest): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == intent.DeleteIntentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_intent_async_from_dict(): + await test_delete_intent_async(request_type=dict) + + +def test_delete_intent_field_headers(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = intent.DeleteIntentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_intent), + '__call__') as call: + call.return_value = None + client.delete_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_intent_field_headers_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = intent.DeleteIntentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_intent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_intent_flattened(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_intent), + '__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_intent( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_intent_flattened_error(): + client = IntentsClient( + credentials=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_intent( + intent.DeleteIntentRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_intent_flattened_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_intent), + '__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_intent( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_intent_flattened_error_async(): + client = IntentsAsyncClient( + credentials=ga_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_intent( + intent.DeleteIntentRequest(), + name='name_value', + ) + + +def test_batch_update_intents(transport: str = 'grpc', request_type=intent.BatchUpdateIntentsRequest): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_intents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.batch_update_intents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == intent.BatchUpdateIntentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_update_intents_from_dict(): + test_batch_update_intents(request_type=dict) + + +def test_batch_update_intents_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_intents), + '__call__') as call: + client.batch_update_intents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == intent.BatchUpdateIntentsRequest() + + +@pytest.mark.asyncio +async def test_batch_update_intents_async(transport: str = 'grpc_asyncio', request_type=intent.BatchUpdateIntentsRequest): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_intents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.batch_update_intents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == intent.BatchUpdateIntentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_update_intents_async_from_dict(): + await test_batch_update_intents_async(request_type=dict) + + +def test_batch_update_intents_field_headers(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = intent.BatchUpdateIntentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_intents), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.batch_update_intents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_batch_update_intents_field_headers_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = intent.BatchUpdateIntentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_intents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.batch_update_intents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_batch_update_intents_flattened(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_intents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_update_intents( + parent='parent_value', + intent_batch_uri='intent_batch_uri_value', + intent_batch_inline=intent.IntentBatch(intents=[intent.Intent(name='name_value')]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + assert args[0].intent_batch_inline == intent.IntentBatch(intents=[intent.Intent(name='name_value')]) + + +def test_batch_update_intents_flattened_error(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_update_intents( + intent.BatchUpdateIntentsRequest(), + parent='parent_value', + intent_batch_uri='intent_batch_uri_value', + intent_batch_inline=intent.IntentBatch(intents=[intent.Intent(name='name_value')]), + ) + + +@pytest.mark.asyncio +async def test_batch_update_intents_flattened_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_intents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_update_intents( + parent='parent_value', + intent_batch_uri='intent_batch_uri_value', + intent_batch_inline=intent.IntentBatch(intents=[intent.Intent(name='name_value')]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + assert args[0].intent_batch_inline == intent.IntentBatch(intents=[intent.Intent(name='name_value')]) + + +@pytest.mark.asyncio +async def test_batch_update_intents_flattened_error_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_update_intents( + intent.BatchUpdateIntentsRequest(), + parent='parent_value', + intent_batch_uri='intent_batch_uri_value', + intent_batch_inline=intent.IntentBatch(intents=[intent.Intent(name='name_value')]), + ) + + +def test_batch_delete_intents(transport: str = 'grpc', request_type=intent.BatchDeleteIntentsRequest): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_intents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.batch_delete_intents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == intent.BatchDeleteIntentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_delete_intents_from_dict(): + test_batch_delete_intents(request_type=dict) + + +def test_batch_delete_intents_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_intents), + '__call__') as call: + client.batch_delete_intents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == intent.BatchDeleteIntentsRequest() + + +@pytest.mark.asyncio +async def test_batch_delete_intents_async(transport: str = 'grpc_asyncio', request_type=intent.BatchDeleteIntentsRequest): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_intents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.batch_delete_intents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == intent.BatchDeleteIntentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_delete_intents_async_from_dict(): + await test_batch_delete_intents_async(request_type=dict) + + +def test_batch_delete_intents_field_headers(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = intent.BatchDeleteIntentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_intents), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.batch_delete_intents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_batch_delete_intents_field_headers_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = intent.BatchDeleteIntentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_intents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.batch_delete_intents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_batch_delete_intents_flattened(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_intents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_delete_intents( + parent='parent_value', + intents=[intent.Intent(name='name_value')], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].intents + mock_val = [intent.Intent(name='name_value')] + assert arg == mock_val + + +def test_batch_delete_intents_flattened_error(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_delete_intents( + intent.BatchDeleteIntentsRequest(), + parent='parent_value', + intents=[intent.Intent(name='name_value')], + ) + + +@pytest.mark.asyncio +async def test_batch_delete_intents_flattened_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_intents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_delete_intents( + parent='parent_value', + intents=[intent.Intent(name='name_value')], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].intents + mock_val = [intent.Intent(name='name_value')] + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_batch_delete_intents_flattened_error_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_delete_intents( + intent.BatchDeleteIntentsRequest(), + parent='parent_value', + intents=[intent.Intent(name='name_value')], + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.IntentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.IntentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = IntentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.IntentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = IntentsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.IntentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = IntentsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.IntentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.IntentsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.IntentsGrpcTransport, + transports.IntentsGrpcAsyncIOTransport, +]) +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 = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.IntentsGrpcTransport, + ) + +def test_intents_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.IntentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_intents_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2beta1.services.intents.transports.IntentsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.IntentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_intents', + 'get_intent', + 'create_intent', + 'update_intent', + 'delete_intent', + 'batch_update_intents', + 'batch_delete_intents', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +def test_intents_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.dialogflow_v2beta1.services.intents.transports.IntentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.IntentsTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_intents_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.dialogflow_v2beta1.services.intents.transports.IntentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.IntentsTransport() + adc.assert_called_once() + + +def test_intents_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) + IntentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.IntentsGrpcTransport, + transports.IntentsGrpcAsyncIOTransport, + ], +) +def test_intents_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.IntentsGrpcTransport, grpc_helpers), + (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_intents_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport]) +def test_intents_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_intents_host_no_port(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_intents_host_with_port(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_intents_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.IntentsGrpcTransport( + 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_intents_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.IntentsGrpcAsyncIOTransport( + 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.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport]) +def test_intents_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.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport]) +def test_intents_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_intents_grpc_lro_client(): + client = IntentsClient( + 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_intents_grpc_lro_async_client(): + client = IntentsAsyncClient( + 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_context_path(): + project = "squid" + session = "clam" + context = "whelk" + expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) + actual = IntentsClient.context_path(project, session, context) + assert expected == actual + + +def test_parse_context_path(): + expected = { + "project": "octopus", + "session": "oyster", + "context": "nudibranch", + } + path = IntentsClient.context_path(**expected) + + # Check that the path construction is reversible. + actual = IntentsClient.parse_context_path(path) + assert expected == actual + +def test_intent_path(): + project = "cuttlefish" + intent = "mussel" + expected = "projects/{project}/agent/intents/{intent}".format(project=project, intent=intent, ) + actual = IntentsClient.intent_path(project, intent) + assert expected == actual + + +def test_parse_intent_path(): + expected = { + "project": "winkle", + "intent": "nautilus", + } + path = IntentsClient.intent_path(**expected) + + # Check that the path construction is reversible. + actual = IntentsClient.parse_intent_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = IntentsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = IntentsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = IntentsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = IntentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = IntentsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = IntentsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = IntentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = IntentsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = IntentsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = IntentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = IntentsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = IntentsClient.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 = IntentsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = IntentsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = IntentsClient.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.IntentsTransport, '_prep_wrapped_messages') as prep: + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.IntentsTransport, '_prep_wrapped_messages') as prep: + transport_class = IntentsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = IntentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = IntentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_knowledge_bases.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_knowledge_bases.py new file mode 100644 index 000000000..2a1b0e974 --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_knowledge_bases.py @@ -0,0 +1,2321 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.knowledge_bases import KnowledgeBasesAsyncClient +from google.cloud.dialogflow_v2beta1.services.knowledge_bases import KnowledgeBasesClient +from google.cloud.dialogflow_v2beta1.services.knowledge_bases import pagers +from google.cloud.dialogflow_v2beta1.services.knowledge_bases import transports +from google.cloud.dialogflow_v2beta1.types import knowledge_base +from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert KnowledgeBasesClient._get_default_mtls_endpoint(None) is None + assert KnowledgeBasesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert KnowledgeBasesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert KnowledgeBasesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert KnowledgeBasesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert KnowledgeBasesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + KnowledgeBasesClient, + KnowledgeBasesAsyncClient, +]) +def test_knowledge_bases_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.KnowledgeBasesGrpcTransport, "grpc"), + (transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_knowledge_bases_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + KnowledgeBasesClient, + KnowledgeBasesAsyncClient, +]) +def test_knowledge_bases_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 == 'dialogflow.googleapis.com:443' + + +def test_knowledge_bases_client_get_transport_class(): + transport = KnowledgeBasesClient.get_transport_class() + available_transports = [ + transports.KnowledgeBasesGrpcTransport, + ] + assert transport in available_transports + + transport = KnowledgeBasesClient.get_transport_class("grpc") + assert transport == transports.KnowledgeBasesGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc"), + (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(KnowledgeBasesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KnowledgeBasesClient)) +@mock.patch.object(KnowledgeBasesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KnowledgeBasesAsyncClient)) +def test_knowledge_bases_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(KnowledgeBasesClient, '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(KnowledgeBasesClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc", "true"), + (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc", "false"), + (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(KnowledgeBasesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KnowledgeBasesClient)) +@mock.patch.object(KnowledgeBasesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KnowledgeBasesAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_knowledge_bases_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc"), + (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_knowledge_bases_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc"), + (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_knowledge_bases_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_knowledge_bases_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2beta1.services.knowledge_bases.transports.KnowledgeBasesGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = KnowledgeBasesClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_knowledge_bases(transport: str = 'grpc', request_type=knowledge_base.ListKnowledgeBasesRequest): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_knowledge_bases), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = knowledge_base.ListKnowledgeBasesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_knowledge_bases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == knowledge_base.ListKnowledgeBasesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListKnowledgeBasesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_knowledge_bases_from_dict(): + test_list_knowledge_bases(request_type=dict) + + +def test_list_knowledge_bases_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = KnowledgeBasesClient( + credentials=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_knowledge_bases), + '__call__') as call: + client.list_knowledge_bases() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == knowledge_base.ListKnowledgeBasesRequest() + + +@pytest.mark.asyncio +async def test_list_knowledge_bases_async(transport: str = 'grpc_asyncio', request_type=knowledge_base.ListKnowledgeBasesRequest): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_knowledge_bases), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(knowledge_base.ListKnowledgeBasesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_knowledge_bases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == knowledge_base.ListKnowledgeBasesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListKnowledgeBasesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_knowledge_bases_async_from_dict(): + await test_list_knowledge_bases_async(request_type=dict) + + +def test_list_knowledge_bases_field_headers(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = knowledge_base.ListKnowledgeBasesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_knowledge_bases), + '__call__') as call: + call.return_value = knowledge_base.ListKnowledgeBasesResponse() + client.list_knowledge_bases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_knowledge_bases_field_headers_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = knowledge_base.ListKnowledgeBasesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_knowledge_bases), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(knowledge_base.ListKnowledgeBasesResponse()) + await client.list_knowledge_bases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_knowledge_bases_flattened(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_knowledge_bases), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = knowledge_base.ListKnowledgeBasesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_knowledge_bases( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_knowledge_bases_flattened_error(): + client = KnowledgeBasesClient( + credentials=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_knowledge_bases( + knowledge_base.ListKnowledgeBasesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_knowledge_bases_flattened_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_knowledge_bases), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = knowledge_base.ListKnowledgeBasesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(knowledge_base.ListKnowledgeBasesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_knowledge_bases( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_knowledge_bases_flattened_error_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_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_knowledge_bases( + knowledge_base.ListKnowledgeBasesRequest(), + parent='parent_value', + ) + + +def test_list_knowledge_bases_pager(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_knowledge_bases), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[ + knowledge_base.KnowledgeBase(), + knowledge_base.KnowledgeBase(), + knowledge_base.KnowledgeBase(), + ], + next_page_token='abc', + ), + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[], + next_page_token='def', + ), + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[ + knowledge_base.KnowledgeBase(), + ], + next_page_token='ghi', + ), + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[ + knowledge_base.KnowledgeBase(), + knowledge_base.KnowledgeBase(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_knowledge_bases(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, knowledge_base.KnowledgeBase) + for i in results) + +def test_list_knowledge_bases_pages(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_knowledge_bases), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[ + knowledge_base.KnowledgeBase(), + knowledge_base.KnowledgeBase(), + knowledge_base.KnowledgeBase(), + ], + next_page_token='abc', + ), + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[], + next_page_token='def', + ), + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[ + knowledge_base.KnowledgeBase(), + ], + next_page_token='ghi', + ), + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[ + knowledge_base.KnowledgeBase(), + knowledge_base.KnowledgeBase(), + ], + ), + RuntimeError, + ) + pages = list(client.list_knowledge_bases(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_knowledge_bases_async_pager(): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_knowledge_bases), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[ + knowledge_base.KnowledgeBase(), + knowledge_base.KnowledgeBase(), + knowledge_base.KnowledgeBase(), + ], + next_page_token='abc', + ), + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[], + next_page_token='def', + ), + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[ + knowledge_base.KnowledgeBase(), + ], + next_page_token='ghi', + ), + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[ + knowledge_base.KnowledgeBase(), + knowledge_base.KnowledgeBase(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_knowledge_bases(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, knowledge_base.KnowledgeBase) + for i in responses) + +@pytest.mark.asyncio +async def test_list_knowledge_bases_async_pages(): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_knowledge_bases), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[ + knowledge_base.KnowledgeBase(), + knowledge_base.KnowledgeBase(), + knowledge_base.KnowledgeBase(), + ], + next_page_token='abc', + ), + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[], + next_page_token='def', + ), + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[ + knowledge_base.KnowledgeBase(), + ], + next_page_token='ghi', + ), + knowledge_base.ListKnowledgeBasesResponse( + knowledge_bases=[ + knowledge_base.KnowledgeBase(), + knowledge_base.KnowledgeBase(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_knowledge_bases(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_knowledge_base(transport: str = 'grpc', request_type=knowledge_base.GetKnowledgeBaseRequest): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = knowledge_base.KnowledgeBase( + name='name_value', + display_name='display_name_value', + language_code='language_code_value', + ) + response = client.get_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == knowledge_base.GetKnowledgeBaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, knowledge_base.KnowledgeBase) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.language_code == 'language_code_value' + + +def test_get_knowledge_base_from_dict(): + test_get_knowledge_base(request_type=dict) + + +def test_get_knowledge_base_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = KnowledgeBasesClient( + credentials=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_knowledge_base), + '__call__') as call: + client.get_knowledge_base() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == knowledge_base.GetKnowledgeBaseRequest() + + +@pytest.mark.asyncio +async def test_get_knowledge_base_async(transport: str = 'grpc_asyncio', request_type=knowledge_base.GetKnowledgeBaseRequest): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(knowledge_base.KnowledgeBase( + name='name_value', + display_name='display_name_value', + language_code='language_code_value', + )) + response = await client.get_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == knowledge_base.GetKnowledgeBaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, knowledge_base.KnowledgeBase) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_get_knowledge_base_async_from_dict(): + await test_get_knowledge_base_async(request_type=dict) + + +def test_get_knowledge_base_field_headers(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = knowledge_base.GetKnowledgeBaseRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_knowledge_base), + '__call__') as call: + call.return_value = knowledge_base.KnowledgeBase() + client.get_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_knowledge_base_field_headers_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = knowledge_base.GetKnowledgeBaseRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_knowledge_base), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(knowledge_base.KnowledgeBase()) + await client.get_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_knowledge_base_flattened(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = knowledge_base.KnowledgeBase() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_knowledge_base( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_knowledge_base_flattened_error(): + client = KnowledgeBasesClient( + credentials=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_knowledge_base( + knowledge_base.GetKnowledgeBaseRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_knowledge_base_flattened_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = knowledge_base.KnowledgeBase() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(knowledge_base.KnowledgeBase()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_knowledge_base( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_knowledge_base_flattened_error_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_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_knowledge_base( + knowledge_base.GetKnowledgeBaseRequest(), + name='name_value', + ) + + +def test_create_knowledge_base(transport: str = 'grpc', request_type=gcd_knowledge_base.CreateKnowledgeBaseRequest): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_knowledge_base.KnowledgeBase( + name='name_value', + display_name='display_name_value', + language_code='language_code_value', + ) + response = client.create_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_knowledge_base.CreateKnowledgeBaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_knowledge_base.KnowledgeBase) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.language_code == 'language_code_value' + + +def test_create_knowledge_base_from_dict(): + test_create_knowledge_base(request_type=dict) + + +def test_create_knowledge_base_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = KnowledgeBasesClient( + credentials=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_knowledge_base), + '__call__') as call: + client.create_knowledge_base() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_knowledge_base.CreateKnowledgeBaseRequest() + + +@pytest.mark.asyncio +async def test_create_knowledge_base_async(transport: str = 'grpc_asyncio', request_type=gcd_knowledge_base.CreateKnowledgeBaseRequest): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_knowledge_base.KnowledgeBase( + name='name_value', + display_name='display_name_value', + language_code='language_code_value', + )) + response = await client.create_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_knowledge_base.CreateKnowledgeBaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_knowledge_base.KnowledgeBase) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_create_knowledge_base_async_from_dict(): + await test_create_knowledge_base_async(request_type=dict) + + +def test_create_knowledge_base_field_headers(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_knowledge_base.CreateKnowledgeBaseRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_knowledge_base), + '__call__') as call: + call.return_value = gcd_knowledge_base.KnowledgeBase() + client.create_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_knowledge_base_field_headers_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_knowledge_base.CreateKnowledgeBaseRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_knowledge_base), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_knowledge_base.KnowledgeBase()) + await client.create_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_knowledge_base_flattened(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_knowledge_base.KnowledgeBase() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_knowledge_base( + parent='parent_value', + knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].knowledge_base + mock_val = gcd_knowledge_base.KnowledgeBase(name='name_value') + assert arg == mock_val + + +def test_create_knowledge_base_flattened_error(): + client = KnowledgeBasesClient( + credentials=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_knowledge_base( + gcd_knowledge_base.CreateKnowledgeBaseRequest(), + parent='parent_value', + knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_knowledge_base_flattened_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_knowledge_base.KnowledgeBase() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_knowledge_base.KnowledgeBase()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_knowledge_base( + parent='parent_value', + knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].knowledge_base + mock_val = gcd_knowledge_base.KnowledgeBase(name='name_value') + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_knowledge_base_flattened_error_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_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_knowledge_base( + gcd_knowledge_base.CreateKnowledgeBaseRequest(), + parent='parent_value', + knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), + ) + + +def test_delete_knowledge_base(transport: str = 'grpc', request_type=knowledge_base.DeleteKnowledgeBaseRequest): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == knowledge_base.DeleteKnowledgeBaseRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_knowledge_base_from_dict(): + test_delete_knowledge_base(request_type=dict) + + +def test_delete_knowledge_base_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = KnowledgeBasesClient( + credentials=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_knowledge_base), + '__call__') as call: + client.delete_knowledge_base() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == knowledge_base.DeleteKnowledgeBaseRequest() + + +@pytest.mark.asyncio +async def test_delete_knowledge_base_async(transport: str = 'grpc_asyncio', request_type=knowledge_base.DeleteKnowledgeBaseRequest): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == knowledge_base.DeleteKnowledgeBaseRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_knowledge_base_async_from_dict(): + await test_delete_knowledge_base_async(request_type=dict) + + +def test_delete_knowledge_base_field_headers(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = knowledge_base.DeleteKnowledgeBaseRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_knowledge_base), + '__call__') as call: + call.return_value = None + client.delete_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_knowledge_base_field_headers_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = knowledge_base.DeleteKnowledgeBaseRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_knowledge_base), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_knowledge_base_flattened(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_knowledge_base), + '__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_knowledge_base( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_knowledge_base_flattened_error(): + client = KnowledgeBasesClient( + credentials=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_knowledge_base( + knowledge_base.DeleteKnowledgeBaseRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_knowledge_base_flattened_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_knowledge_base), + '__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_knowledge_base( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_knowledge_base_flattened_error_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_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_knowledge_base( + knowledge_base.DeleteKnowledgeBaseRequest(), + name='name_value', + ) + + +def test_update_knowledge_base(transport: str = 'grpc', request_type=gcd_knowledge_base.UpdateKnowledgeBaseRequest): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_knowledge_base.KnowledgeBase( + name='name_value', + display_name='display_name_value', + language_code='language_code_value', + ) + response = client.update_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_knowledge_base.UpdateKnowledgeBaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_knowledge_base.KnowledgeBase) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.language_code == 'language_code_value' + + +def test_update_knowledge_base_from_dict(): + test_update_knowledge_base(request_type=dict) + + +def test_update_knowledge_base_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = KnowledgeBasesClient( + credentials=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_knowledge_base), + '__call__') as call: + client.update_knowledge_base() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_knowledge_base.UpdateKnowledgeBaseRequest() + + +@pytest.mark.asyncio +async def test_update_knowledge_base_async(transport: str = 'grpc_asyncio', request_type=gcd_knowledge_base.UpdateKnowledgeBaseRequest): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_knowledge_base.KnowledgeBase( + name='name_value', + display_name='display_name_value', + language_code='language_code_value', + )) + response = await client.update_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_knowledge_base.UpdateKnowledgeBaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_knowledge_base.KnowledgeBase) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_update_knowledge_base_async_from_dict(): + await test_update_knowledge_base_async(request_type=dict) + + +def test_update_knowledge_base_field_headers(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_knowledge_base.UpdateKnowledgeBaseRequest() + + request.knowledge_base.name = 'knowledge_base.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_knowledge_base), + '__call__') as call: + call.return_value = gcd_knowledge_base.KnowledgeBase() + client.update_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'knowledge_base.name=knowledge_base.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_knowledge_base_field_headers_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_knowledge_base.UpdateKnowledgeBaseRequest() + + request.knowledge_base.name = 'knowledge_base.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_knowledge_base), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_knowledge_base.KnowledgeBase()) + await client.update_knowledge_base(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'knowledge_base.name=knowledge_base.name/value', + ) in kw['metadata'] + + +def test_update_knowledge_base_flattened(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_knowledge_base.KnowledgeBase() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_knowledge_base( + knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].knowledge_base + mock_val = gcd_knowledge_base.KnowledgeBase(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_knowledge_base_flattened_error(): + client = KnowledgeBasesClient( + credentials=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_knowledge_base( + gcd_knowledge_base.UpdateKnowledgeBaseRequest(), + knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_knowledge_base_flattened_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_knowledge_base), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_knowledge_base.KnowledgeBase() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_knowledge_base.KnowledgeBase()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_knowledge_base( + knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].knowledge_base + mock_val = gcd_knowledge_base.KnowledgeBase(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_knowledge_base_flattened_error_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_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_knowledge_base( + gcd_knowledge_base.UpdateKnowledgeBaseRequest(), + knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.KnowledgeBasesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.KnowledgeBasesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = KnowledgeBasesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.KnowledgeBasesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = KnowledgeBasesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.KnowledgeBasesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = KnowledgeBasesClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.KnowledgeBasesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.KnowledgeBasesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.KnowledgeBasesGrpcTransport, + transports.KnowledgeBasesGrpcAsyncIOTransport, +]) +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 = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.KnowledgeBasesGrpcTransport, + ) + +def test_knowledge_bases_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.KnowledgeBasesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_knowledge_bases_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2beta1.services.knowledge_bases.transports.KnowledgeBasesTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.KnowledgeBasesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_knowledge_bases', + 'get_knowledge_base', + 'create_knowledge_base', + 'delete_knowledge_base', + 'update_knowledge_base', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_knowledge_bases_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.dialogflow_v2beta1.services.knowledge_bases.transports.KnowledgeBasesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.KnowledgeBasesTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_knowledge_bases_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.dialogflow_v2beta1.services.knowledge_bases.transports.KnowledgeBasesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.KnowledgeBasesTransport() + adc.assert_called_once() + + +def test_knowledge_bases_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) + KnowledgeBasesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.KnowledgeBasesGrpcTransport, + transports.KnowledgeBasesGrpcAsyncIOTransport, + ], +) +def test_knowledge_bases_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.KnowledgeBasesGrpcTransport, grpc_helpers), + (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_knowledge_bases_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.KnowledgeBasesGrpcTransport, transports.KnowledgeBasesGrpcAsyncIOTransport]) +def test_knowledge_bases_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_knowledge_bases_host_no_port(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_knowledge_bases_host_with_port(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_knowledge_bases_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.KnowledgeBasesGrpcTransport( + 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_knowledge_bases_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.KnowledgeBasesGrpcAsyncIOTransport( + 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.KnowledgeBasesGrpcTransport, transports.KnowledgeBasesGrpcAsyncIOTransport]) +def test_knowledge_bases_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.KnowledgeBasesGrpcTransport, transports.KnowledgeBasesGrpcAsyncIOTransport]) +def test_knowledge_bases_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_knowledge_base_path(): + project = "squid" + knowledge_base = "clam" + expected = "projects/{project}/knowledgeBases/{knowledge_base}".format(project=project, knowledge_base=knowledge_base, ) + actual = KnowledgeBasesClient.knowledge_base_path(project, knowledge_base) + assert expected == actual + + +def test_parse_knowledge_base_path(): + expected = { + "project": "whelk", + "knowledge_base": "octopus", + } + path = KnowledgeBasesClient.knowledge_base_path(**expected) + + # Check that the path construction is reversible. + actual = KnowledgeBasesClient.parse_knowledge_base_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = KnowledgeBasesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = KnowledgeBasesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = KnowledgeBasesClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = KnowledgeBasesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = KnowledgeBasesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = KnowledgeBasesClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = KnowledgeBasesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = KnowledgeBasesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = KnowledgeBasesClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = KnowledgeBasesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = KnowledgeBasesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = KnowledgeBasesClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = KnowledgeBasesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = KnowledgeBasesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = KnowledgeBasesClient.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.KnowledgeBasesTransport, '_prep_wrapped_messages') as prep: + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.KnowledgeBasesTransport, '_prep_wrapped_messages') as prep: + transport_class = KnowledgeBasesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = KnowledgeBasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_participants.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_participants.py new file mode 100644 index 000000000..8756f48a2 --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_participants.py @@ -0,0 +1,3665 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.participants import ParticipantsAsyncClient +from google.cloud.dialogflow_v2beta1.services.participants import ParticipantsClient +from google.cloud.dialogflow_v2beta1.services.participants import pagers +from google.cloud.dialogflow_v2beta1.services.participants import transports +from google.cloud.dialogflow_v2beta1.types import agent +from google.cloud.dialogflow_v2beta1.types import audio_config +from google.cloud.dialogflow_v2beta1.types import context +from google.cloud.dialogflow_v2beta1.types import entity_type +from google.cloud.dialogflow_v2beta1.types import participant +from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant +from google.cloud.dialogflow_v2beta1.types import session +from google.cloud.dialogflow_v2beta1.types import session_entity_type +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ParticipantsClient._get_default_mtls_endpoint(None) is None + assert ParticipantsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ParticipantsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ParticipantsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ParticipantsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ParticipantsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + ParticipantsClient, + ParticipantsAsyncClient, +]) +def test_participants_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ParticipantsGrpcTransport, "grpc"), + (transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_participants_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + ParticipantsClient, + ParticipantsAsyncClient, +]) +def test_participants_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 == 'dialogflow.googleapis.com:443' + + +def test_participants_client_get_transport_class(): + transport = ParticipantsClient.get_transport_class() + available_transports = [ + transports.ParticipantsGrpcTransport, + ] + assert transport in available_transports + + transport = ParticipantsClient.get_transport_class("grpc") + assert transport == transports.ParticipantsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc"), + (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ParticipantsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ParticipantsClient)) +@mock.patch.object(ParticipantsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ParticipantsAsyncClient)) +def test_participants_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(ParticipantsClient, '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(ParticipantsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc", "true"), + (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc", "false"), + (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ParticipantsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ParticipantsClient)) +@mock.patch.object(ParticipantsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ParticipantsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_participants_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc"), + (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_participants_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc"), + (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_participants_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_participants_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2beta1.services.participants.transports.ParticipantsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ParticipantsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_create_participant(transport: str = 'grpc', request_type=gcd_participant.CreateParticipantRequest): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_participant), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_participant.Participant( + name='name_value', + role=gcd_participant.Participant.Role.HUMAN_AGENT, + obfuscated_external_user_id='obfuscated_external_user_id_value', + ) + response = client.create_participant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_participant.CreateParticipantRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_participant.Participant) + assert response.name == 'name_value' + assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT + assert response.obfuscated_external_user_id == 'obfuscated_external_user_id_value' + + +def test_create_participant_from_dict(): + test_create_participant(request_type=dict) + + +def test_create_participant_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ParticipantsClient( + credentials=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_participant), + '__call__') as call: + client.create_participant() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_participant.CreateParticipantRequest() + + +@pytest.mark.asyncio +async def test_create_participant_async(transport: str = 'grpc_asyncio', request_type=gcd_participant.CreateParticipantRequest): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_participant), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.Participant( + name='name_value', + role=gcd_participant.Participant.Role.HUMAN_AGENT, + obfuscated_external_user_id='obfuscated_external_user_id_value', + )) + response = await client.create_participant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_participant.CreateParticipantRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_participant.Participant) + assert response.name == 'name_value' + assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT + assert response.obfuscated_external_user_id == 'obfuscated_external_user_id_value' + + +@pytest.mark.asyncio +async def test_create_participant_async_from_dict(): + await test_create_participant_async(request_type=dict) + + +def test_create_participant_field_headers(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_participant.CreateParticipantRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_participant), + '__call__') as call: + call.return_value = gcd_participant.Participant() + client.create_participant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_participant_field_headers_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_participant.CreateParticipantRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_participant), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.Participant()) + await client.create_participant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_participant_flattened(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_participant), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_participant.Participant() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_participant( + parent='parent_value', + participant=gcd_participant.Participant(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].participant + mock_val = gcd_participant.Participant(name='name_value') + assert arg == mock_val + + +def test_create_participant_flattened_error(): + client = ParticipantsClient( + credentials=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_participant( + gcd_participant.CreateParticipantRequest(), + parent='parent_value', + participant=gcd_participant.Participant(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_participant_flattened_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_participant), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_participant.Participant() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.Participant()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_participant( + parent='parent_value', + participant=gcd_participant.Participant(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].participant + mock_val = gcd_participant.Participant(name='name_value') + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_participant_flattened_error_async(): + client = ParticipantsAsyncClient( + credentials=ga_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_participant( + gcd_participant.CreateParticipantRequest(), + parent='parent_value', + participant=gcd_participant.Participant(name='name_value'), + ) + + +def test_get_participant(transport: str = 'grpc', request_type=participant.GetParticipantRequest): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_participant), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.Participant( + name='name_value', + role=participant.Participant.Role.HUMAN_AGENT, + obfuscated_external_user_id='obfuscated_external_user_id_value', + ) + response = client.get_participant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == participant.GetParticipantRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, participant.Participant) + assert response.name == 'name_value' + assert response.role == participant.Participant.Role.HUMAN_AGENT + assert response.obfuscated_external_user_id == 'obfuscated_external_user_id_value' + + +def test_get_participant_from_dict(): + test_get_participant(request_type=dict) + + +def test_get_participant_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ParticipantsClient( + credentials=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_participant), + '__call__') as call: + client.get_participant() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == participant.GetParticipantRequest() + + +@pytest.mark.asyncio +async def test_get_participant_async(transport: str = 'grpc_asyncio', request_type=participant.GetParticipantRequest): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_participant), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(participant.Participant( + name='name_value', + role=participant.Participant.Role.HUMAN_AGENT, + obfuscated_external_user_id='obfuscated_external_user_id_value', + )) + response = await client.get_participant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == participant.GetParticipantRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, participant.Participant) + assert response.name == 'name_value' + assert response.role == participant.Participant.Role.HUMAN_AGENT + assert response.obfuscated_external_user_id == 'obfuscated_external_user_id_value' + + +@pytest.mark.asyncio +async def test_get_participant_async_from_dict(): + await test_get_participant_async(request_type=dict) + + +def test_get_participant_field_headers(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = participant.GetParticipantRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_participant), + '__call__') as call: + call.return_value = participant.Participant() + client.get_participant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_participant_field_headers_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = participant.GetParticipantRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_participant), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.Participant()) + await client.get_participant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_participant_flattened(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_participant), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.Participant() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_participant( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_participant_flattened_error(): + client = ParticipantsClient( + credentials=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_participant( + participant.GetParticipantRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_participant_flattened_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_participant), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.Participant() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.Participant()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_participant( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_participant_flattened_error_async(): + client = ParticipantsAsyncClient( + credentials=ga_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_participant( + participant.GetParticipantRequest(), + name='name_value', + ) + + +def test_list_participants(transport: str = 'grpc', request_type=participant.ListParticipantsRequest): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_participants), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.ListParticipantsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_participants(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == participant.ListParticipantsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListParticipantsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_participants_from_dict(): + test_list_participants(request_type=dict) + + +def test_list_participants_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ParticipantsClient( + credentials=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_participants), + '__call__') as call: + client.list_participants() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == participant.ListParticipantsRequest() + + +@pytest.mark.asyncio +async def test_list_participants_async(transport: str = 'grpc_asyncio', request_type=participant.ListParticipantsRequest): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_participants), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(participant.ListParticipantsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_participants(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == participant.ListParticipantsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListParticipantsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_participants_async_from_dict(): + await test_list_participants_async(request_type=dict) + + +def test_list_participants_field_headers(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = participant.ListParticipantsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_participants), + '__call__') as call: + call.return_value = participant.ListParticipantsResponse() + client.list_participants(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_participants_field_headers_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = participant.ListParticipantsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_participants), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.ListParticipantsResponse()) + await client.list_participants(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_participants_flattened(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_participants), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.ListParticipantsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_participants( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_participants_flattened_error(): + client = ParticipantsClient( + credentials=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_participants( + participant.ListParticipantsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_participants_flattened_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_participants), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.ListParticipantsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.ListParticipantsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_participants( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_participants_flattened_error_async(): + client = ParticipantsAsyncClient( + credentials=ga_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_participants( + participant.ListParticipantsRequest(), + parent='parent_value', + ) + + +def test_list_participants_pager(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_participants), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + participant.ListParticipantsResponse( + participants=[ + participant.Participant(), + participant.Participant(), + participant.Participant(), + ], + next_page_token='abc', + ), + participant.ListParticipantsResponse( + participants=[], + next_page_token='def', + ), + participant.ListParticipantsResponse( + participants=[ + participant.Participant(), + ], + next_page_token='ghi', + ), + participant.ListParticipantsResponse( + participants=[ + participant.Participant(), + participant.Participant(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_participants(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, participant.Participant) + for i in results) + +def test_list_participants_pages(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_participants), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + participant.ListParticipantsResponse( + participants=[ + participant.Participant(), + participant.Participant(), + participant.Participant(), + ], + next_page_token='abc', + ), + participant.ListParticipantsResponse( + participants=[], + next_page_token='def', + ), + participant.ListParticipantsResponse( + participants=[ + participant.Participant(), + ], + next_page_token='ghi', + ), + participant.ListParticipantsResponse( + participants=[ + participant.Participant(), + participant.Participant(), + ], + ), + RuntimeError, + ) + pages = list(client.list_participants(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_participants_async_pager(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_participants), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + participant.ListParticipantsResponse( + participants=[ + participant.Participant(), + participant.Participant(), + participant.Participant(), + ], + next_page_token='abc', + ), + participant.ListParticipantsResponse( + participants=[], + next_page_token='def', + ), + participant.ListParticipantsResponse( + participants=[ + participant.Participant(), + ], + next_page_token='ghi', + ), + participant.ListParticipantsResponse( + participants=[ + participant.Participant(), + participant.Participant(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_participants(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, participant.Participant) + for i in responses) + +@pytest.mark.asyncio +async def test_list_participants_async_pages(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_participants), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + participant.ListParticipantsResponse( + participants=[ + participant.Participant(), + participant.Participant(), + participant.Participant(), + ], + next_page_token='abc', + ), + participant.ListParticipantsResponse( + participants=[], + next_page_token='def', + ), + participant.ListParticipantsResponse( + participants=[ + participant.Participant(), + ], + next_page_token='ghi', + ), + participant.ListParticipantsResponse( + participants=[ + participant.Participant(), + participant.Participant(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_participants(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_participant(transport: str = 'grpc', request_type=gcd_participant.UpdateParticipantRequest): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_participant), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_participant.Participant( + name='name_value', + role=gcd_participant.Participant.Role.HUMAN_AGENT, + obfuscated_external_user_id='obfuscated_external_user_id_value', + ) + response = client.update_participant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_participant.UpdateParticipantRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_participant.Participant) + assert response.name == 'name_value' + assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT + assert response.obfuscated_external_user_id == 'obfuscated_external_user_id_value' + + +def test_update_participant_from_dict(): + test_update_participant(request_type=dict) + + +def test_update_participant_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ParticipantsClient( + credentials=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_participant), + '__call__') as call: + client.update_participant() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_participant.UpdateParticipantRequest() + + +@pytest.mark.asyncio +async def test_update_participant_async(transport: str = 'grpc_asyncio', request_type=gcd_participant.UpdateParticipantRequest): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_participant), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.Participant( + name='name_value', + role=gcd_participant.Participant.Role.HUMAN_AGENT, + obfuscated_external_user_id='obfuscated_external_user_id_value', + )) + response = await client.update_participant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_participant.UpdateParticipantRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_participant.Participant) + assert response.name == 'name_value' + assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT + assert response.obfuscated_external_user_id == 'obfuscated_external_user_id_value' + + +@pytest.mark.asyncio +async def test_update_participant_async_from_dict(): + await test_update_participant_async(request_type=dict) + + +def test_update_participant_field_headers(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_participant.UpdateParticipantRequest() + + request.participant.name = 'participant.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_participant), + '__call__') as call: + call.return_value = gcd_participant.Participant() + client.update_participant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'participant.name=participant.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_participant_field_headers_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_participant.UpdateParticipantRequest() + + request.participant.name = 'participant.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_participant), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.Participant()) + await client.update_participant(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'participant.name=participant.name/value', + ) in kw['metadata'] + + +def test_update_participant_flattened(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_participant), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_participant.Participant() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_participant( + participant=gcd_participant.Participant(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].participant + mock_val = gcd_participant.Participant(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_participant_flattened_error(): + client = ParticipantsClient( + credentials=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_participant( + gcd_participant.UpdateParticipantRequest(), + participant=gcd_participant.Participant(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_participant_flattened_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_participant), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_participant.Participant() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.Participant()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_participant( + participant=gcd_participant.Participant(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].participant + mock_val = gcd_participant.Participant(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_participant_flattened_error_async(): + client = ParticipantsAsyncClient( + credentials=ga_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_participant( + gcd_participant.UpdateParticipantRequest(), + participant=gcd_participant.Participant(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_analyze_content(transport: str = 'grpc', request_type=gcd_participant.AnalyzeContentRequest): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_content), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_participant.AnalyzeContentResponse( + reply_text='reply_text_value', + ) + response = client.analyze_content(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_participant.AnalyzeContentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_participant.AnalyzeContentResponse) + assert response.reply_text == 'reply_text_value' + + +def test_analyze_content_from_dict(): + test_analyze_content(request_type=dict) + + +def test_analyze_content_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_content), + '__call__') as call: + client.analyze_content() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_participant.AnalyzeContentRequest() + + +@pytest.mark.asyncio +async def test_analyze_content_async(transport: str = 'grpc_asyncio', request_type=gcd_participant.AnalyzeContentRequest): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_content), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.AnalyzeContentResponse( + reply_text='reply_text_value', + )) + response = await client.analyze_content(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_participant.AnalyzeContentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_participant.AnalyzeContentResponse) + assert response.reply_text == 'reply_text_value' + + +@pytest.mark.asyncio +async def test_analyze_content_async_from_dict(): + await test_analyze_content_async(request_type=dict) + + +def test_analyze_content_field_headers(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_participant.AnalyzeContentRequest() + + request.participant = 'participant/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_content), + '__call__') as call: + call.return_value = gcd_participant.AnalyzeContentResponse() + client.analyze_content(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'participant=participant/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_analyze_content_field_headers_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_participant.AnalyzeContentRequest() + + request.participant = 'participant/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_content), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.AnalyzeContentResponse()) + await client.analyze_content(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'participant=participant/value', + ) in kw['metadata'] + + +def test_analyze_content_flattened(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_content), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_participant.AnalyzeContentResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.analyze_content( + participant='participant_value', + text_input=session.TextInput(text='text_value'), + event_input=session.EventInput(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].participant + mock_val = 'participant_value' + assert arg == mock_val + assert args[0].event_input == session.EventInput(name='name_value') + + +def test_analyze_content_flattened_error(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.analyze_content( + gcd_participant.AnalyzeContentRequest(), + participant='participant_value', + text_input=session.TextInput(text='text_value'), + event_input=session.EventInput(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_analyze_content_flattened_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_content), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_participant.AnalyzeContentResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.AnalyzeContentResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.analyze_content( + participant='participant_value', + text_input=session.TextInput(text='text_value'), + event_input=session.EventInput(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].participant + mock_val = 'participant_value' + assert arg == mock_val + assert args[0].event_input == session.EventInput(name='name_value') + + +@pytest.mark.asyncio +async def test_analyze_content_flattened_error_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.analyze_content( + gcd_participant.AnalyzeContentRequest(), + participant='participant_value', + text_input=session.TextInput(text='text_value'), + event_input=session.EventInput(name='name_value'), + ) + + +def test_suggest_articles(transport: str = 'grpc', request_type=participant.SuggestArticlesRequest): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_articles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.SuggestArticlesResponse( + latest_message='latest_message_value', + context_size=1311, + ) + response = client.suggest_articles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == participant.SuggestArticlesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, participant.SuggestArticlesResponse) + assert response.latest_message == 'latest_message_value' + assert response.context_size == 1311 + + +def test_suggest_articles_from_dict(): + test_suggest_articles(request_type=dict) + + +def test_suggest_articles_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_articles), + '__call__') as call: + client.suggest_articles() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == participant.SuggestArticlesRequest() + + +@pytest.mark.asyncio +async def test_suggest_articles_async(transport: str = 'grpc_asyncio', request_type=participant.SuggestArticlesRequest): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_articles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestArticlesResponse( + latest_message='latest_message_value', + context_size=1311, + )) + response = await client.suggest_articles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == participant.SuggestArticlesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, participant.SuggestArticlesResponse) + assert response.latest_message == 'latest_message_value' + assert response.context_size == 1311 + + +@pytest.mark.asyncio +async def test_suggest_articles_async_from_dict(): + await test_suggest_articles_async(request_type=dict) + + +def test_suggest_articles_field_headers(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = participant.SuggestArticlesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_articles), + '__call__') as call: + call.return_value = participant.SuggestArticlesResponse() + client.suggest_articles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_suggest_articles_field_headers_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = participant.SuggestArticlesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_articles), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestArticlesResponse()) + await client.suggest_articles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_suggest_articles_flattened(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_articles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.SuggestArticlesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.suggest_articles( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_suggest_articles_flattened_error(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.suggest_articles( + participant.SuggestArticlesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_suggest_articles_flattened_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_articles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.SuggestArticlesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestArticlesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.suggest_articles( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_suggest_articles_flattened_error_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.suggest_articles( + participant.SuggestArticlesRequest(), + parent='parent_value', + ) + + +def test_suggest_faq_answers(transport: str = 'grpc', request_type=participant.SuggestFaqAnswersRequest): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_faq_answers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.SuggestFaqAnswersResponse( + latest_message='latest_message_value', + context_size=1311, + ) + response = client.suggest_faq_answers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == participant.SuggestFaqAnswersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, participant.SuggestFaqAnswersResponse) + assert response.latest_message == 'latest_message_value' + assert response.context_size == 1311 + + +def test_suggest_faq_answers_from_dict(): + test_suggest_faq_answers(request_type=dict) + + +def test_suggest_faq_answers_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_faq_answers), + '__call__') as call: + client.suggest_faq_answers() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == participant.SuggestFaqAnswersRequest() + + +@pytest.mark.asyncio +async def test_suggest_faq_answers_async(transport: str = 'grpc_asyncio', request_type=participant.SuggestFaqAnswersRequest): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_faq_answers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestFaqAnswersResponse( + latest_message='latest_message_value', + context_size=1311, + )) + response = await client.suggest_faq_answers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == participant.SuggestFaqAnswersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, participant.SuggestFaqAnswersResponse) + assert response.latest_message == 'latest_message_value' + assert response.context_size == 1311 + + +@pytest.mark.asyncio +async def test_suggest_faq_answers_async_from_dict(): + await test_suggest_faq_answers_async(request_type=dict) + + +def test_suggest_faq_answers_field_headers(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = participant.SuggestFaqAnswersRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_faq_answers), + '__call__') as call: + call.return_value = participant.SuggestFaqAnswersResponse() + client.suggest_faq_answers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_suggest_faq_answers_field_headers_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = participant.SuggestFaqAnswersRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_faq_answers), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestFaqAnswersResponse()) + await client.suggest_faq_answers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_suggest_faq_answers_flattened(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_faq_answers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.SuggestFaqAnswersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.suggest_faq_answers( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_suggest_faq_answers_flattened_error(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.suggest_faq_answers( + participant.SuggestFaqAnswersRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_suggest_faq_answers_flattened_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_faq_answers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.SuggestFaqAnswersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestFaqAnswersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.suggest_faq_answers( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_suggest_faq_answers_flattened_error_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.suggest_faq_answers( + participant.SuggestFaqAnswersRequest(), + parent='parent_value', + ) + + +def test_suggest_smart_replies(transport: str = 'grpc', request_type=participant.SuggestSmartRepliesRequest): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_smart_replies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.SuggestSmartRepliesResponse( + latest_message='latest_message_value', + context_size=1311, + ) + response = client.suggest_smart_replies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == participant.SuggestSmartRepliesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, participant.SuggestSmartRepliesResponse) + assert response.latest_message == 'latest_message_value' + assert response.context_size == 1311 + + +def test_suggest_smart_replies_from_dict(): + test_suggest_smart_replies(request_type=dict) + + +def test_suggest_smart_replies_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_smart_replies), + '__call__') as call: + client.suggest_smart_replies() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == participant.SuggestSmartRepliesRequest() + + +@pytest.mark.asyncio +async def test_suggest_smart_replies_async(transport: str = 'grpc_asyncio', request_type=participant.SuggestSmartRepliesRequest): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_smart_replies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestSmartRepliesResponse( + latest_message='latest_message_value', + context_size=1311, + )) + response = await client.suggest_smart_replies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == participant.SuggestSmartRepliesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, participant.SuggestSmartRepliesResponse) + assert response.latest_message == 'latest_message_value' + assert response.context_size == 1311 + + +@pytest.mark.asyncio +async def test_suggest_smart_replies_async_from_dict(): + await test_suggest_smart_replies_async(request_type=dict) + + +def test_suggest_smart_replies_field_headers(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = participant.SuggestSmartRepliesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_smart_replies), + '__call__') as call: + call.return_value = participant.SuggestSmartRepliesResponse() + client.suggest_smart_replies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_suggest_smart_replies_field_headers_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = participant.SuggestSmartRepliesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_smart_replies), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestSmartRepliesResponse()) + await client.suggest_smart_replies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_suggest_smart_replies_flattened(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_smart_replies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.SuggestSmartRepliesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.suggest_smart_replies( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_suggest_smart_replies_flattened_error(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.suggest_smart_replies( + participant.SuggestSmartRepliesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_suggest_smart_replies_flattened_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.suggest_smart_replies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.SuggestSmartRepliesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestSmartRepliesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.suggest_smart_replies( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_suggest_smart_replies_flattened_error_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.suggest_smart_replies( + participant.SuggestSmartRepliesRequest(), + parent='parent_value', + ) + + +def test_list_suggestions(transport: str = 'grpc', request_type=participant.ListSuggestionsRequest): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_suggestions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.ListSuggestionsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_suggestions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == participant.ListSuggestionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSuggestionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_suggestions_from_dict(): + test_list_suggestions(request_type=dict) + + +def test_list_suggestions_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ParticipantsClient( + credentials=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_suggestions), + '__call__') as call: + client.list_suggestions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == participant.ListSuggestionsRequest() + + +@pytest.mark.asyncio +async def test_list_suggestions_async(transport: str = 'grpc_asyncio', request_type=participant.ListSuggestionsRequest): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_suggestions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(participant.ListSuggestionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_suggestions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == participant.ListSuggestionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSuggestionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_suggestions_async_from_dict(): + await test_list_suggestions_async(request_type=dict) + + +def test_list_suggestions_field_headers(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = participant.ListSuggestionsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_suggestions), + '__call__') as call: + call.return_value = participant.ListSuggestionsResponse() + client.list_suggestions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_suggestions_field_headers_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = participant.ListSuggestionsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_suggestions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.ListSuggestionsResponse()) + await client.list_suggestions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_suggestions_pager(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_suggestions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + participant.ListSuggestionsResponse( + suggestions=[ + participant.Suggestion(), + participant.Suggestion(), + participant.Suggestion(), + ], + next_page_token='abc', + ), + participant.ListSuggestionsResponse( + suggestions=[], + next_page_token='def', + ), + participant.ListSuggestionsResponse( + suggestions=[ + participant.Suggestion(), + ], + next_page_token='ghi', + ), + participant.ListSuggestionsResponse( + suggestions=[ + participant.Suggestion(), + participant.Suggestion(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_suggestions(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, participant.Suggestion) + for i in results) + +def test_list_suggestions_pages(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_suggestions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + participant.ListSuggestionsResponse( + suggestions=[ + participant.Suggestion(), + participant.Suggestion(), + participant.Suggestion(), + ], + next_page_token='abc', + ), + participant.ListSuggestionsResponse( + suggestions=[], + next_page_token='def', + ), + participant.ListSuggestionsResponse( + suggestions=[ + participant.Suggestion(), + ], + next_page_token='ghi', + ), + participant.ListSuggestionsResponse( + suggestions=[ + participant.Suggestion(), + participant.Suggestion(), + ], + ), + RuntimeError, + ) + pages = list(client.list_suggestions(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_suggestions_async_pager(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_suggestions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + participant.ListSuggestionsResponse( + suggestions=[ + participant.Suggestion(), + participant.Suggestion(), + participant.Suggestion(), + ], + next_page_token='abc', + ), + participant.ListSuggestionsResponse( + suggestions=[], + next_page_token='def', + ), + participant.ListSuggestionsResponse( + suggestions=[ + participant.Suggestion(), + ], + next_page_token='ghi', + ), + participant.ListSuggestionsResponse( + suggestions=[ + participant.Suggestion(), + participant.Suggestion(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_suggestions(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, participant.Suggestion) + for i in responses) + +@pytest.mark.asyncio +async def test_list_suggestions_async_pages(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_suggestions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + participant.ListSuggestionsResponse( + suggestions=[ + participant.Suggestion(), + participant.Suggestion(), + participant.Suggestion(), + ], + next_page_token='abc', + ), + participant.ListSuggestionsResponse( + suggestions=[], + next_page_token='def', + ), + participant.ListSuggestionsResponse( + suggestions=[ + participant.Suggestion(), + ], + next_page_token='ghi', + ), + participant.ListSuggestionsResponse( + suggestions=[ + participant.Suggestion(), + participant.Suggestion(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_suggestions(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_compile_suggestion(transport: str = 'grpc', request_type=participant.CompileSuggestionRequest): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compile_suggestion), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = participant.CompileSuggestionResponse( + latest_message='latest_message_value', + context_size=1311, + ) + response = client.compile_suggestion(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == participant.CompileSuggestionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, participant.CompileSuggestionResponse) + assert response.latest_message == 'latest_message_value' + assert response.context_size == 1311 + + +def test_compile_suggestion_from_dict(): + test_compile_suggestion(request_type=dict) + + +def test_compile_suggestion_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compile_suggestion), + '__call__') as call: + client.compile_suggestion() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == participant.CompileSuggestionRequest() + + +@pytest.mark.asyncio +async def test_compile_suggestion_async(transport: str = 'grpc_asyncio', request_type=participant.CompileSuggestionRequest): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compile_suggestion), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(participant.CompileSuggestionResponse( + latest_message='latest_message_value', + context_size=1311, + )) + response = await client.compile_suggestion(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == participant.CompileSuggestionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, participant.CompileSuggestionResponse) + assert response.latest_message == 'latest_message_value' + assert response.context_size == 1311 + + +@pytest.mark.asyncio +async def test_compile_suggestion_async_from_dict(): + await test_compile_suggestion_async(request_type=dict) + + +def test_compile_suggestion_field_headers(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = participant.CompileSuggestionRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compile_suggestion), + '__call__') as call: + call.return_value = participant.CompileSuggestionResponse() + client.compile_suggestion(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_compile_suggestion_field_headers_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = participant.CompileSuggestionRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compile_suggestion), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.CompileSuggestionResponse()) + await client.compile_suggestion(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ParticipantsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ParticipantsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ParticipantsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ParticipantsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ParticipantsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ParticipantsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ParticipantsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ParticipantsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ParticipantsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ParticipantsGrpcTransport, + transports.ParticipantsGrpcAsyncIOTransport, +]) +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 = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ParticipantsGrpcTransport, + ) + +def test_participants_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ParticipantsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_participants_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2beta1.services.participants.transports.ParticipantsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ParticipantsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_participant', + 'get_participant', + 'list_participants', + 'update_participant', + 'analyze_content', + 'suggest_articles', + 'suggest_faq_answers', + 'suggest_smart_replies', + 'list_suggestions', + 'compile_suggestion', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_participants_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.dialogflow_v2beta1.services.participants.transports.ParticipantsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ParticipantsTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_participants_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.dialogflow_v2beta1.services.participants.transports.ParticipantsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ParticipantsTransport() + adc.assert_called_once() + + +def test_participants_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) + ParticipantsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ParticipantsGrpcTransport, + transports.ParticipantsGrpcAsyncIOTransport, + ], +) +def test_participants_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ParticipantsGrpcTransport, grpc_helpers), + (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_participants_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ParticipantsGrpcTransport, transports.ParticipantsGrpcAsyncIOTransport]) +def test_participants_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_participants_host_no_port(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_participants_host_with_port(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_participants_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ParticipantsGrpcTransport( + 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_participants_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ParticipantsGrpcAsyncIOTransport( + 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.ParticipantsGrpcTransport, transports.ParticipantsGrpcAsyncIOTransport]) +def test_participants_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.ParticipantsGrpcTransport, transports.ParticipantsGrpcAsyncIOTransport]) +def test_participants_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_context_path(): + project = "squid" + session = "clam" + context = "whelk" + expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) + actual = ParticipantsClient.context_path(project, session, context) + assert expected == actual + + +def test_parse_context_path(): + expected = { + "project": "octopus", + "session": "oyster", + "context": "nudibranch", + } + path = ParticipantsClient.context_path(**expected) + + # Check that the path construction is reversible. + actual = ParticipantsClient.parse_context_path(path) + assert expected == actual + +def test_document_path(): + project = "cuttlefish" + knowledge_base = "mussel" + document = "winkle" + expected = "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format(project=project, knowledge_base=knowledge_base, document=document, ) + actual = ParticipantsClient.document_path(project, knowledge_base, document) + assert expected == actual + + +def test_parse_document_path(): + expected = { + "project": "nautilus", + "knowledge_base": "scallop", + "document": "abalone", + } + path = ParticipantsClient.document_path(**expected) + + # Check that the path construction is reversible. + actual = ParticipantsClient.parse_document_path(path) + assert expected == actual + +def test_intent_path(): + project = "squid" + intent = "clam" + expected = "projects/{project}/agent/intents/{intent}".format(project=project, intent=intent, ) + actual = ParticipantsClient.intent_path(project, intent) + assert expected == actual + + +def test_parse_intent_path(): + expected = { + "project": "whelk", + "intent": "octopus", + } + path = ParticipantsClient.intent_path(**expected) + + # Check that the path construction is reversible. + actual = ParticipantsClient.parse_intent_path(path) + assert expected == actual + +def test_message_path(): + project = "oyster" + conversation = "nudibranch" + message = "cuttlefish" + expected = "projects/{project}/conversations/{conversation}/messages/{message}".format(project=project, conversation=conversation, message=message, ) + actual = ParticipantsClient.message_path(project, conversation, message) + assert expected == actual + + +def test_parse_message_path(): + expected = { + "project": "mussel", + "conversation": "winkle", + "message": "nautilus", + } + path = ParticipantsClient.message_path(**expected) + + # Check that the path construction is reversible. + actual = ParticipantsClient.parse_message_path(path) + assert expected == actual + +def test_participant_path(): + project = "scallop" + conversation = "abalone" + participant = "squid" + expected = "projects/{project}/conversations/{conversation}/participants/{participant}".format(project=project, conversation=conversation, participant=participant, ) + actual = ParticipantsClient.participant_path(project, conversation, participant) + assert expected == actual + + +def test_parse_participant_path(): + expected = { + "project": "clam", + "conversation": "whelk", + "participant": "octopus", + } + path = ParticipantsClient.participant_path(**expected) + + # Check that the path construction is reversible. + actual = ParticipantsClient.parse_participant_path(path) + assert expected == actual + +def test_session_entity_type_path(): + project = "oyster" + session = "nudibranch" + entity_type = "cuttlefish" + expected = "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format(project=project, session=session, entity_type=entity_type, ) + actual = ParticipantsClient.session_entity_type_path(project, session, entity_type) + assert expected == actual + + +def test_parse_session_entity_type_path(): + expected = { + "project": "mussel", + "session": "winkle", + "entity_type": "nautilus", + } + path = ParticipantsClient.session_entity_type_path(**expected) + + # Check that the path construction is reversible. + actual = ParticipantsClient.parse_session_entity_type_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ParticipantsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = ParticipantsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ParticipantsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = ParticipantsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = ParticipantsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ParticipantsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ParticipantsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = ParticipantsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ParticipantsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = ParticipantsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = ParticipantsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ParticipantsClient.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 = ParticipantsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = ParticipantsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ParticipantsClient.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.ParticipantsTransport, '_prep_wrapped_messages') as prep: + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ParticipantsTransport, '_prep_wrapped_messages') as prep: + transport_class = ParticipantsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = ParticipantsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = ParticipantsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_session_entity_types.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_session_entity_types.py new file mode 100644 index 000000000..c8a56f090 --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_session_entity_types.py @@ -0,0 +1,2312 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.session_entity_types import SessionEntityTypesAsyncClient +from google.cloud.dialogflow_v2beta1.services.session_entity_types import SessionEntityTypesClient +from google.cloud.dialogflow_v2beta1.services.session_entity_types import pagers +from google.cloud.dialogflow_v2beta1.services.session_entity_types import transports +from google.cloud.dialogflow_v2beta1.types import entity_type +from google.cloud.dialogflow_v2beta1.types import session_entity_type +from google.cloud.dialogflow_v2beta1.types import session_entity_type as gcd_session_entity_type +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SessionEntityTypesClient._get_default_mtls_endpoint(None) is None + assert SessionEntityTypesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SessionEntityTypesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SessionEntityTypesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SessionEntityTypesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SessionEntityTypesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + SessionEntityTypesClient, + SessionEntityTypesAsyncClient, +]) +def test_session_entity_types_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SessionEntityTypesGrpcTransport, "grpc"), + (transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_session_entity_types_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + SessionEntityTypesClient, + SessionEntityTypesAsyncClient, +]) +def test_session_entity_types_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 == 'dialogflow.googleapis.com:443' + + +def test_session_entity_types_client_get_transport_class(): + transport = SessionEntityTypesClient.get_transport_class() + available_transports = [ + transports.SessionEntityTypesGrpcTransport, + ] + assert transport in available_transports + + transport = SessionEntityTypesClient.get_transport_class("grpc") + assert transport == transports.SessionEntityTypesGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc"), + (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(SessionEntityTypesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionEntityTypesClient)) +@mock.patch.object(SessionEntityTypesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionEntityTypesAsyncClient)) +def test_session_entity_types_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(SessionEntityTypesClient, '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(SessionEntityTypesClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc", "true"), + (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc", "false"), + (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(SessionEntityTypesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionEntityTypesClient)) +@mock.patch.object(SessionEntityTypesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionEntityTypesAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_session_entity_types_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc"), + (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_session_entity_types_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc"), + (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_session_entity_types_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_session_entity_types_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2beta1.services.session_entity_types.transports.SessionEntityTypesGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SessionEntityTypesClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_session_entity_types(transport: str = 'grpc', request_type=session_entity_type.ListSessionEntityTypesRequest): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_session_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = session_entity_type.ListSessionEntityTypesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_session_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == session_entity_type.ListSessionEntityTypesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSessionEntityTypesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_session_entity_types_from_dict(): + test_list_session_entity_types(request_type=dict) + + +def test_list_session_entity_types_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SessionEntityTypesClient( + credentials=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_session_entity_types), + '__call__') as call: + client.list_session_entity_types() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == session_entity_type.ListSessionEntityTypesRequest() + + +@pytest.mark.asyncio +async def test_list_session_entity_types_async(transport: str = 'grpc_asyncio', request_type=session_entity_type.ListSessionEntityTypesRequest): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_session_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(session_entity_type.ListSessionEntityTypesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_session_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == session_entity_type.ListSessionEntityTypesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSessionEntityTypesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_session_entity_types_async_from_dict(): + await test_list_session_entity_types_async(request_type=dict) + + +def test_list_session_entity_types_field_headers(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = session_entity_type.ListSessionEntityTypesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_session_entity_types), + '__call__') as call: + call.return_value = session_entity_type.ListSessionEntityTypesResponse() + client.list_session_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_session_entity_types_field_headers_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = session_entity_type.ListSessionEntityTypesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_session_entity_types), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(session_entity_type.ListSessionEntityTypesResponse()) + await client.list_session_entity_types(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_session_entity_types_flattened(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_session_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = session_entity_type.ListSessionEntityTypesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_session_entity_types( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_session_entity_types_flattened_error(): + client = SessionEntityTypesClient( + credentials=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_session_entity_types( + session_entity_type.ListSessionEntityTypesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_session_entity_types_flattened_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_session_entity_types), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = session_entity_type.ListSessionEntityTypesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(session_entity_type.ListSessionEntityTypesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_session_entity_types( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_session_entity_types_flattened_error_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_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_session_entity_types( + session_entity_type.ListSessionEntityTypesRequest(), + parent='parent_value', + ) + + +def test_list_session_entity_types_pager(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_session_entity_types), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[ + session_entity_type.SessionEntityType(), + session_entity_type.SessionEntityType(), + session_entity_type.SessionEntityType(), + ], + next_page_token='abc', + ), + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[], + next_page_token='def', + ), + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[ + session_entity_type.SessionEntityType(), + ], + next_page_token='ghi', + ), + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[ + session_entity_type.SessionEntityType(), + session_entity_type.SessionEntityType(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_session_entity_types(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, session_entity_type.SessionEntityType) + for i in results) + +def test_list_session_entity_types_pages(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_session_entity_types), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[ + session_entity_type.SessionEntityType(), + session_entity_type.SessionEntityType(), + session_entity_type.SessionEntityType(), + ], + next_page_token='abc', + ), + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[], + next_page_token='def', + ), + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[ + session_entity_type.SessionEntityType(), + ], + next_page_token='ghi', + ), + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[ + session_entity_type.SessionEntityType(), + session_entity_type.SessionEntityType(), + ], + ), + RuntimeError, + ) + pages = list(client.list_session_entity_types(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_session_entity_types_async_pager(): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_session_entity_types), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[ + session_entity_type.SessionEntityType(), + session_entity_type.SessionEntityType(), + session_entity_type.SessionEntityType(), + ], + next_page_token='abc', + ), + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[], + next_page_token='def', + ), + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[ + session_entity_type.SessionEntityType(), + ], + next_page_token='ghi', + ), + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[ + session_entity_type.SessionEntityType(), + session_entity_type.SessionEntityType(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_session_entity_types(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, session_entity_type.SessionEntityType) + for i in responses) + +@pytest.mark.asyncio +async def test_list_session_entity_types_async_pages(): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_session_entity_types), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[ + session_entity_type.SessionEntityType(), + session_entity_type.SessionEntityType(), + session_entity_type.SessionEntityType(), + ], + next_page_token='abc', + ), + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[], + next_page_token='def', + ), + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[ + session_entity_type.SessionEntityType(), + ], + next_page_token='ghi', + ), + session_entity_type.ListSessionEntityTypesResponse( + session_entity_types=[ + session_entity_type.SessionEntityType(), + session_entity_type.SessionEntityType(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_session_entity_types(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_session_entity_type(transport: str = 'grpc', request_type=session_entity_type.GetSessionEntityTypeRequest): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = session_entity_type.SessionEntityType( + name='name_value', + entity_override_mode=session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, + ) + response = client.get_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == session_entity_type.GetSessionEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, session_entity_type.SessionEntityType) + assert response.name == 'name_value' + assert response.entity_override_mode == session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE + + +def test_get_session_entity_type_from_dict(): + test_get_session_entity_type(request_type=dict) + + +def test_get_session_entity_type_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SessionEntityTypesClient( + credentials=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_session_entity_type), + '__call__') as call: + client.get_session_entity_type() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == session_entity_type.GetSessionEntityTypeRequest() + + +@pytest.mark.asyncio +async def test_get_session_entity_type_async(transport: str = 'grpc_asyncio', request_type=session_entity_type.GetSessionEntityTypeRequest): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(session_entity_type.SessionEntityType( + name='name_value', + entity_override_mode=session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, + )) + response = await client.get_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == session_entity_type.GetSessionEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, session_entity_type.SessionEntityType) + assert response.name == 'name_value' + assert response.entity_override_mode == session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE + + +@pytest.mark.asyncio +async def test_get_session_entity_type_async_from_dict(): + await test_get_session_entity_type_async(request_type=dict) + + +def test_get_session_entity_type_field_headers(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = session_entity_type.GetSessionEntityTypeRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_session_entity_type), + '__call__') as call: + call.return_value = session_entity_type.SessionEntityType() + client.get_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_session_entity_type_field_headers_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = session_entity_type.GetSessionEntityTypeRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_session_entity_type), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(session_entity_type.SessionEntityType()) + await client.get_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_session_entity_type_flattened(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = session_entity_type.SessionEntityType() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_session_entity_type( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_session_entity_type_flattened_error(): + client = SessionEntityTypesClient( + credentials=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_session_entity_type( + session_entity_type.GetSessionEntityTypeRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_session_entity_type_flattened_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = session_entity_type.SessionEntityType() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(session_entity_type.SessionEntityType()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_session_entity_type( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_session_entity_type_flattened_error_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_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_session_entity_type( + session_entity_type.GetSessionEntityTypeRequest(), + name='name_value', + ) + + +def test_create_session_entity_type(transport: str = 'grpc', request_type=gcd_session_entity_type.CreateSessionEntityTypeRequest): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_session_entity_type.SessionEntityType( + name='name_value', + entity_override_mode=gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, + ) + response = client.create_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_session_entity_type.CreateSessionEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_session_entity_type.SessionEntityType) + assert response.name == 'name_value' + assert response.entity_override_mode == gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE + + +def test_create_session_entity_type_from_dict(): + test_create_session_entity_type(request_type=dict) + + +def test_create_session_entity_type_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SessionEntityTypesClient( + credentials=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_session_entity_type), + '__call__') as call: + client.create_session_entity_type() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_session_entity_type.CreateSessionEntityTypeRequest() + + +@pytest.mark.asyncio +async def test_create_session_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcd_session_entity_type.CreateSessionEntityTypeRequest): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_session_entity_type.SessionEntityType( + name='name_value', + entity_override_mode=gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, + )) + response = await client.create_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_session_entity_type.CreateSessionEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_session_entity_type.SessionEntityType) + assert response.name == 'name_value' + assert response.entity_override_mode == gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE + + +@pytest.mark.asyncio +async def test_create_session_entity_type_async_from_dict(): + await test_create_session_entity_type_async(request_type=dict) + + +def test_create_session_entity_type_field_headers(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_session_entity_type.CreateSessionEntityTypeRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_session_entity_type), + '__call__') as call: + call.return_value = gcd_session_entity_type.SessionEntityType() + client.create_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_session_entity_type_field_headers_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_session_entity_type.CreateSessionEntityTypeRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_session_entity_type), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_session_entity_type.SessionEntityType()) + await client.create_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_session_entity_type_flattened(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_session_entity_type.SessionEntityType() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_session_entity_type( + parent='parent_value', + session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].session_entity_type + mock_val = gcd_session_entity_type.SessionEntityType(name='name_value') + assert arg == mock_val + + +def test_create_session_entity_type_flattened_error(): + client = SessionEntityTypesClient( + credentials=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_session_entity_type( + gcd_session_entity_type.CreateSessionEntityTypeRequest(), + parent='parent_value', + session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_session_entity_type_flattened_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_session_entity_type.SessionEntityType() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_session_entity_type.SessionEntityType()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_session_entity_type( + parent='parent_value', + session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].session_entity_type + mock_val = gcd_session_entity_type.SessionEntityType(name='name_value') + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_session_entity_type_flattened_error_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_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_session_entity_type( + gcd_session_entity_type.CreateSessionEntityTypeRequest(), + parent='parent_value', + session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), + ) + + +def test_update_session_entity_type(transport: str = 'grpc', request_type=gcd_session_entity_type.UpdateSessionEntityTypeRequest): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_session_entity_type.SessionEntityType( + name='name_value', + entity_override_mode=gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, + ) + response = client.update_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_session_entity_type.UpdateSessionEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_session_entity_type.SessionEntityType) + assert response.name == 'name_value' + assert response.entity_override_mode == gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE + + +def test_update_session_entity_type_from_dict(): + test_update_session_entity_type(request_type=dict) + + +def test_update_session_entity_type_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SessionEntityTypesClient( + credentials=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_session_entity_type), + '__call__') as call: + client.update_session_entity_type() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_session_entity_type.UpdateSessionEntityTypeRequest() + + +@pytest.mark.asyncio +async def test_update_session_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcd_session_entity_type.UpdateSessionEntityTypeRequest): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_session_entity_type.SessionEntityType( + name='name_value', + entity_override_mode=gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, + )) + response = await client.update_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_session_entity_type.UpdateSessionEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_session_entity_type.SessionEntityType) + assert response.name == 'name_value' + assert response.entity_override_mode == gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE + + +@pytest.mark.asyncio +async def test_update_session_entity_type_async_from_dict(): + await test_update_session_entity_type_async(request_type=dict) + + +def test_update_session_entity_type_field_headers(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_session_entity_type.UpdateSessionEntityTypeRequest() + + request.session_entity_type.name = 'session_entity_type.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_session_entity_type), + '__call__') as call: + call.return_value = gcd_session_entity_type.SessionEntityType() + client.update_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'session_entity_type.name=session_entity_type.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_session_entity_type_field_headers_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_session_entity_type.UpdateSessionEntityTypeRequest() + + request.session_entity_type.name = 'session_entity_type.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_session_entity_type), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_session_entity_type.SessionEntityType()) + await client.update_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'session_entity_type.name=session_entity_type.name/value', + ) in kw['metadata'] + + +def test_update_session_entity_type_flattened(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_session_entity_type.SessionEntityType() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_session_entity_type( + session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].session_entity_type + mock_val = gcd_session_entity_type.SessionEntityType(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_session_entity_type_flattened_error(): + client = SessionEntityTypesClient( + credentials=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_session_entity_type( + gcd_session_entity_type.UpdateSessionEntityTypeRequest(), + session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_session_entity_type_flattened_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_session_entity_type.SessionEntityType() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_session_entity_type.SessionEntityType()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_session_entity_type( + session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].session_entity_type + mock_val = gcd_session_entity_type.SessionEntityType(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_session_entity_type_flattened_error_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_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_session_entity_type( + gcd_session_entity_type.UpdateSessionEntityTypeRequest(), + session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_session_entity_type(transport: str = 'grpc', request_type=session_entity_type.DeleteSessionEntityTypeRequest): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == session_entity_type.DeleteSessionEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_session_entity_type_from_dict(): + test_delete_session_entity_type(request_type=dict) + + +def test_delete_session_entity_type_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SessionEntityTypesClient( + credentials=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_session_entity_type), + '__call__') as call: + client.delete_session_entity_type() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == session_entity_type.DeleteSessionEntityTypeRequest() + + +@pytest.mark.asyncio +async def test_delete_session_entity_type_async(transport: str = 'grpc_asyncio', request_type=session_entity_type.DeleteSessionEntityTypeRequest): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_session_entity_type), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == session_entity_type.DeleteSessionEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_session_entity_type_async_from_dict(): + await test_delete_session_entity_type_async(request_type=dict) + + +def test_delete_session_entity_type_field_headers(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = session_entity_type.DeleteSessionEntityTypeRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_session_entity_type), + '__call__') as call: + call.return_value = None + client.delete_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_session_entity_type_field_headers_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = session_entity_type.DeleteSessionEntityTypeRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_session_entity_type), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_session_entity_type_flattened(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_session_entity_type), + '__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_session_entity_type( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_session_entity_type_flattened_error(): + client = SessionEntityTypesClient( + credentials=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_session_entity_type( + session_entity_type.DeleteSessionEntityTypeRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_session_entity_type_flattened_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_session_entity_type), + '__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_session_entity_type( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_session_entity_type_flattened_error_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_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_session_entity_type( + session_entity_type.DeleteSessionEntityTypeRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SessionEntityTypesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SessionEntityTypesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SessionEntityTypesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SessionEntityTypesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SessionEntityTypesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SessionEntityTypesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SessionEntityTypesClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SessionEntityTypesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SessionEntityTypesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SessionEntityTypesGrpcTransport, + transports.SessionEntityTypesGrpcAsyncIOTransport, +]) +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 = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SessionEntityTypesGrpcTransport, + ) + +def test_session_entity_types_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SessionEntityTypesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_session_entity_types_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2beta1.services.session_entity_types.transports.SessionEntityTypesTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SessionEntityTypesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_session_entity_types', + 'get_session_entity_type', + 'create_session_entity_type', + 'update_session_entity_type', + 'delete_session_entity_type', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_session_entity_types_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.dialogflow_v2beta1.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SessionEntityTypesTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_session_entity_types_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.dialogflow_v2beta1.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SessionEntityTypesTransport() + adc.assert_called_once() + + +def test_session_entity_types_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) + SessionEntityTypesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SessionEntityTypesGrpcTransport, + transports.SessionEntityTypesGrpcAsyncIOTransport, + ], +) +def test_session_entity_types_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionEntityTypesGrpcTransport, grpc_helpers), + (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_session_entity_types_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SessionEntityTypesGrpcTransport, transports.SessionEntityTypesGrpcAsyncIOTransport]) +def test_session_entity_types_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_session_entity_types_host_no_port(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_session_entity_types_host_with_port(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_session_entity_types_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SessionEntityTypesGrpcTransport( + 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_session_entity_types_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SessionEntityTypesGrpcAsyncIOTransport( + 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.SessionEntityTypesGrpcTransport, transports.SessionEntityTypesGrpcAsyncIOTransport]) +def test_session_entity_types_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.SessionEntityTypesGrpcTransport, transports.SessionEntityTypesGrpcAsyncIOTransport]) +def test_session_entity_types_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_session_entity_type_path(): + project = "squid" + session = "clam" + entity_type = "whelk" + expected = "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format(project=project, session=session, entity_type=entity_type, ) + actual = SessionEntityTypesClient.session_entity_type_path(project, session, entity_type) + assert expected == actual + + +def test_parse_session_entity_type_path(): + expected = { + "project": "octopus", + "session": "oyster", + "entity_type": "nudibranch", + } + path = SessionEntityTypesClient.session_entity_type_path(**expected) + + # Check that the path construction is reversible. + actual = SessionEntityTypesClient.parse_session_entity_type_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SessionEntityTypesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = SessionEntityTypesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SessionEntityTypesClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = SessionEntityTypesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = SessionEntityTypesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SessionEntityTypesClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SessionEntityTypesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = SessionEntityTypesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SessionEntityTypesClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = SessionEntityTypesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = SessionEntityTypesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SessionEntityTypesClient.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 = SessionEntityTypesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = SessionEntityTypesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SessionEntityTypesClient.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.SessionEntityTypesTransport, '_prep_wrapped_messages') as prep: + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SessionEntityTypesTransport, '_prep_wrapped_messages') as prep: + transport_class = SessionEntityTypesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SessionEntityTypesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_sessions.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_sessions.py new file mode 100644 index 000000000..5b0dd3ca0 --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_sessions.py @@ -0,0 +1,1326 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.sessions import SessionsAsyncClient +from google.cloud.dialogflow_v2beta1.services.sessions import SessionsClient +from google.cloud.dialogflow_v2beta1.services.sessions import transports +from google.cloud.dialogflow_v2beta1.types import agent +from google.cloud.dialogflow_v2beta1.types import audio_config +from google.cloud.dialogflow_v2beta1.types import context +from google.cloud.dialogflow_v2beta1.types import entity_type +from google.cloud.dialogflow_v2beta1.types import session +from google.cloud.dialogflow_v2beta1.types import session as gcd_session +from google.cloud.dialogflow_v2beta1.types import session_entity_type +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SessionsClient._get_default_mtls_endpoint(None) is None + assert SessionsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SessionsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SessionsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SessionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SessionsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + SessionsClient, + SessionsAsyncClient, +]) +def test_sessions_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SessionsGrpcTransport, "grpc"), + (transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_sessions_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + SessionsClient, + SessionsAsyncClient, +]) +def test_sessions_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 == 'dialogflow.googleapis.com:443' + + +def test_sessions_client_get_transport_class(): + transport = SessionsClient.get_transport_class() + available_transports = [ + transports.SessionsGrpcTransport, + ] + assert transport in available_transports + + transport = SessionsClient.get_transport_class("grpc") + assert transport == transports.SessionsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SessionsClient, transports.SessionsGrpcTransport, "grpc"), + (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(SessionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionsClient)) +@mock.patch.object(SessionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionsAsyncClient)) +def test_sessions_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(SessionsClient, '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(SessionsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (SessionsClient, transports.SessionsGrpcTransport, "grpc", "true"), + (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SessionsClient, transports.SessionsGrpcTransport, "grpc", "false"), + (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(SessionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionsClient)) +@mock.patch.object(SessionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_sessions_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SessionsClient, transports.SessionsGrpcTransport, "grpc"), + (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_sessions_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SessionsClient, transports.SessionsGrpcTransport, "grpc"), + (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_sessions_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_sessions_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2beta1.services.sessions.transports.SessionsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SessionsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_detect_intent(transport: str = 'grpc', request_type=gcd_session.DetectIntentRequest): + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.detect_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_session.DetectIntentResponse( + response_id='response_id_value', + output_audio=b'output_audio_blob', + ) + response = client.detect_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_session.DetectIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_session.DetectIntentResponse) + assert response.response_id == 'response_id_value' + assert response.output_audio == b'output_audio_blob' + + +def test_detect_intent_from_dict(): + test_detect_intent(request_type=dict) + + +def test_detect_intent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.detect_intent), + '__call__') as call: + client.detect_intent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_session.DetectIntentRequest() + + +@pytest.mark.asyncio +async def test_detect_intent_async(transport: str = 'grpc_asyncio', request_type=gcd_session.DetectIntentRequest): + client = SessionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.detect_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_session.DetectIntentResponse( + response_id='response_id_value', + output_audio=b'output_audio_blob', + )) + response = await client.detect_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_session.DetectIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_session.DetectIntentResponse) + assert response.response_id == 'response_id_value' + assert response.output_audio == b'output_audio_blob' + + +@pytest.mark.asyncio +async def test_detect_intent_async_from_dict(): + await test_detect_intent_async(request_type=dict) + + +def test_detect_intent_field_headers(): + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_session.DetectIntentRequest() + + request.session = 'session/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.detect_intent), + '__call__') as call: + call.return_value = gcd_session.DetectIntentResponse() + client.detect_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'session=session/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_detect_intent_field_headers_async(): + client = SessionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_session.DetectIntentRequest() + + request.session = 'session/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.detect_intent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_session.DetectIntentResponse()) + await client.detect_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'session=session/value', + ) in kw['metadata'] + + +def test_detect_intent_flattened(): + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.detect_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_session.DetectIntentResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.detect_intent( + session='session_value', + query_input=gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].session + mock_val = 'session_value' + assert arg == mock_val + arg = args[0].query_input + mock_val = gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)) + assert arg == mock_val + + +def test_detect_intent_flattened_error(): + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.detect_intent( + gcd_session.DetectIntentRequest(), + session='session_value', + query_input=gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)), + ) + + +@pytest.mark.asyncio +async def test_detect_intent_flattened_async(): + client = SessionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.detect_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_session.DetectIntentResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_session.DetectIntentResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.detect_intent( + session='session_value', + query_input=gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].session + mock_val = 'session_value' + assert arg == mock_val + arg = args[0].query_input + mock_val = gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_detect_intent_flattened_error_async(): + client = SessionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.detect_intent( + gcd_session.DetectIntentRequest(), + session='session_value', + query_input=gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)), + ) + + +def test_streaming_detect_intent(transport: str = 'grpc', request_type=session.StreamingDetectIntentRequest): + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.streaming_detect_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iter([session.StreamingDetectIntentResponse()]) + response = client.streaming_detect_intent(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, session.StreamingDetectIntentResponse) + + +def test_streaming_detect_intent_from_dict(): + test_streaming_detect_intent(request_type=dict) + + +@pytest.mark.asyncio +async def test_streaming_detect_intent_async(transport: str = 'grpc_asyncio', request_type=session.StreamingDetectIntentRequest): + client = SessionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.streaming_detect_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock(side_effect=[session.StreamingDetectIntentResponse()]) + response = await client.streaming_detect_intent(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, session.StreamingDetectIntentResponse) + + +@pytest.mark.asyncio +async def test_streaming_detect_intent_async_from_dict(): + await test_streaming_detect_intent_async(request_type=dict) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SessionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SessionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SessionsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SessionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SessionsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SessionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SessionsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SessionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SessionsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SessionsGrpcTransport, + transports.SessionsGrpcAsyncIOTransport, +]) +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 = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SessionsGrpcTransport, + ) + +def test_sessions_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SessionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_sessions_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2beta1.services.sessions.transports.SessionsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SessionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'detect_intent', + 'streaming_detect_intent', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_sessions_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.dialogflow_v2beta1.services.sessions.transports.SessionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SessionsTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_sessions_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.dialogflow_v2beta1.services.sessions.transports.SessionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SessionsTransport() + adc.assert_called_once() + + +def test_sessions_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) + SessionsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SessionsGrpcTransport, + transports.SessionsGrpcAsyncIOTransport, + ], +) +def test_sessions_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionsGrpcTransport, grpc_helpers), + (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_sessions_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport]) +def test_sessions_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_sessions_host_no_port(): + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_sessions_host_with_port(): + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_sessions_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SessionsGrpcTransport( + 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_sessions_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SessionsGrpcAsyncIOTransport( + 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.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport]) +def test_sessions_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.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport]) +def test_sessions_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_context_path(): + project = "squid" + session = "clam" + context = "whelk" + expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) + actual = SessionsClient.context_path(project, session, context) + assert expected == actual + + +def test_parse_context_path(): + expected = { + "project": "octopus", + "session": "oyster", + "context": "nudibranch", + } + path = SessionsClient.context_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_context_path(path) + assert expected == actual + +def test_document_path(): + project = "cuttlefish" + knowledge_base = "mussel" + document = "winkle" + expected = "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format(project=project, knowledge_base=knowledge_base, document=document, ) + actual = SessionsClient.document_path(project, knowledge_base, document) + assert expected == actual + + +def test_parse_document_path(): + expected = { + "project": "nautilus", + "knowledge_base": "scallop", + "document": "abalone", + } + path = SessionsClient.document_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_document_path(path) + assert expected == actual + +def test_intent_path(): + project = "squid" + intent = "clam" + expected = "projects/{project}/agent/intents/{intent}".format(project=project, intent=intent, ) + actual = SessionsClient.intent_path(project, intent) + assert expected == actual + + +def test_parse_intent_path(): + expected = { + "project": "whelk", + "intent": "octopus", + } + path = SessionsClient.intent_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_intent_path(path) + assert expected == actual + +def test_session_path(): + project = "oyster" + session = "nudibranch" + expected = "projects/{project}/agent/sessions/{session}".format(project=project, session=session, ) + actual = SessionsClient.session_path(project, session) + assert expected == actual + + +def test_parse_session_path(): + expected = { + "project": "cuttlefish", + "session": "mussel", + } + path = SessionsClient.session_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_session_path(path) + assert expected == actual + +def test_session_entity_type_path(): + project = "winkle" + session = "nautilus" + entity_type = "scallop" + expected = "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format(project=project, session=session, entity_type=entity_type, ) + actual = SessionsClient.session_entity_type_path(project, session, entity_type) + assert expected == actual + + +def test_parse_session_entity_type_path(): + expected = { + "project": "abalone", + "session": "squid", + "entity_type": "clam", + } + path = SessionsClient.session_entity_type_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_session_entity_type_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SessionsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = SessionsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = SessionsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = SessionsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SessionsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = SessionsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = SessionsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = SessionsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = SessionsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = SessionsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.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.SessionsTransport, '_prep_wrapped_messages') as prep: + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SessionsTransport, '_prep_wrapped_messages') as prep: + transport_class = SessionsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SessionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_versions.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_versions.py new file mode 100644 index 000000000..14d07920e --- /dev/null +++ b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_versions.py @@ -0,0 +1,2334 @@ +# -*- 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 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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.versions import VersionsAsyncClient +from google.cloud.dialogflow_v2beta1.services.versions import VersionsClient +from google.cloud.dialogflow_v2beta1.services.versions import pagers +from google.cloud.dialogflow_v2beta1.services.versions import transports +from google.cloud.dialogflow_v2beta1.types import version +from google.cloud.dialogflow_v2beta1.types import version as gcd_version +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert VersionsClient._get_default_mtls_endpoint(None) is None + assert VersionsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert VersionsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert VersionsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert VersionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert VersionsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + VersionsClient, + VersionsAsyncClient, +]) +def test_versions_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 == 'dialogflow.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.VersionsGrpcTransport, "grpc"), + (transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_versions_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + VersionsClient, + VersionsAsyncClient, +]) +def test_versions_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 == 'dialogflow.googleapis.com:443' + + +def test_versions_client_get_transport_class(): + transport = VersionsClient.get_transport_class() + available_transports = [ + transports.VersionsGrpcTransport, + ] + assert transport in available_transports + + transport = VersionsClient.get_transport_class("grpc") + assert transport == transports.VersionsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient)) +@mock.patch.object(VersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsAsyncClient)) +def test_versions_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(VersionsClient, '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(VersionsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # 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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc", "true"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (VersionsClient, transports.VersionsGrpcTransport, "grpc", "false"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient)) +@mock.patch.object(VersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_versions_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(transport=transport_name, client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_versions_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_versions_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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_versions_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflow_v2beta1.services.versions.transports.VersionsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = VersionsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_versions(transport: str = 'grpc', request_type=version.ListVersionsRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = version.ListVersionsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == version.ListVersionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListVersionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_versions_from_dict(): + test_list_versions(request_type=dict) + + +def test_list_versions_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=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_versions), + '__call__') as call: + client.list_versions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == version.ListVersionsRequest() + + +@pytest.mark.asyncio +async def test_list_versions_async(transport: str = 'grpc_asyncio', request_type=version.ListVersionsRequest): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(version.ListVersionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == version.ListVersionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListVersionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_versions_async_from_dict(): + await test_list_versions_async(request_type=dict) + + +def test_list_versions_field_headers(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.ListVersionsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + call.return_value = version.ListVersionsResponse() + client.list_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_versions_field_headers_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.ListVersionsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(version.ListVersionsResponse()) + await client.list_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_versions_flattened(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = version.ListVersionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_versions( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_versions_flattened_error(): + client = VersionsClient( + credentials=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_versions( + version.ListVersionsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_versions_flattened_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = version.ListVersionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(version.ListVersionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_versions( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_versions_flattened_error_async(): + client = VersionsAsyncClient( + credentials=ga_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_versions( + version.ListVersionsRequest(), + parent='parent_value', + ) + + +def test_list_versions_pager(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + version.Version(), + ], + next_page_token='abc', + ), + version.ListVersionsResponse( + versions=[], + next_page_token='def', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + ], + next_page_token='ghi', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_versions(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, version.Version) + for i in results) + +def test_list_versions_pages(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + version.Version(), + ], + next_page_token='abc', + ), + version.ListVersionsResponse( + versions=[], + next_page_token='def', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + ], + next_page_token='ghi', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + ], + ), + RuntimeError, + ) + pages = list(client.list_versions(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_versions_async_pager(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + version.Version(), + ], + next_page_token='abc', + ), + version.ListVersionsResponse( + versions=[], + next_page_token='def', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + ], + next_page_token='ghi', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_versions(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, version.Version) + for i in responses) + +@pytest.mark.asyncio +async def test_list_versions_async_pages(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + version.Version(), + ], + next_page_token='abc', + ), + version.ListVersionsResponse( + versions=[], + next_page_token='def', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + ], + next_page_token='ghi', + ), + version.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_versions(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_version(transport: str = 'grpc', request_type=version.GetVersionRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = version.Version( + name='name_value', + description='description_value', + version_number=1518, + status=version.Version.VersionStatus.IN_PROGRESS, + ) + response = client.get_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == version.GetVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, version.Version) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.version_number == 1518 + assert response.status == version.Version.VersionStatus.IN_PROGRESS + + +def test_get_version_from_dict(): + test_get_version(request_type=dict) + + +def test_get_version_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=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_version), + '__call__') as call: + client.get_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == version.GetVersionRequest() + + +@pytest.mark.asyncio +async def test_get_version_async(transport: str = 'grpc_asyncio', request_type=version.GetVersionRequest): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(version.Version( + name='name_value', + description='description_value', + version_number=1518, + status=version.Version.VersionStatus.IN_PROGRESS, + )) + response = await client.get_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == version.GetVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, version.Version) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.version_number == 1518 + assert response.status == version.Version.VersionStatus.IN_PROGRESS + + +@pytest.mark.asyncio +async def test_get_version_async_from_dict(): + await test_get_version_async(request_type=dict) + + +def test_get_version_field_headers(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.GetVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_version), + '__call__') as call: + call.return_value = version.Version() + client.get_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_version_field_headers_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.GetVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(version.Version()) + await client.get_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_version_flattened(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = version.Version() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_version( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_version_flattened_error(): + client = VersionsClient( + credentials=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_version( + version.GetVersionRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_version_flattened_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = version.Version() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(version.Version()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_version( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_version_flattened_error_async(): + client = VersionsAsyncClient( + credentials=ga_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_version( + version.GetVersionRequest(), + name='name_value', + ) + + +def test_create_version(transport: str = 'grpc', request_type=gcd_version.CreateVersionRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version( + name='name_value', + description='description_value', + version_number=1518, + status=gcd_version.Version.VersionStatus.IN_PROGRESS, + ) + response = client.create_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.CreateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_version.Version) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.version_number == 1518 + assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS + + +def test_create_version_from_dict(): + test_create_version(request_type=dict) + + +def test_create_version_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=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_version), + '__call__') as call: + client.create_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.CreateVersionRequest() + + +@pytest.mark.asyncio +async def test_create_version_async(transport: str = 'grpc_asyncio', request_type=gcd_version.CreateVersionRequest): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version( + name='name_value', + description='description_value', + version_number=1518, + status=gcd_version.Version.VersionStatus.IN_PROGRESS, + )) + response = await client.create_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.CreateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_version.Version) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.version_number == 1518 + assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS + + +@pytest.mark.asyncio +async def test_create_version_async_from_dict(): + await test_create_version_async(request_type=dict) + + +def test_create_version_field_headers(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_version.CreateVersionRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + call.return_value = gcd_version.Version() + client.create_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_version_field_headers_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_version.CreateVersionRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version()) + await client.create_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_version_flattened(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_version( + parent='parent_value', + version=gcd_version.Version(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].version + mock_val = gcd_version.Version(name='name_value') + assert arg == mock_val + + +def test_create_version_flattened_error(): + client = VersionsClient( + credentials=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_version( + gcd_version.CreateVersionRequest(), + parent='parent_value', + version=gcd_version.Version(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_version_flattened_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_version( + parent='parent_value', + version=gcd_version.Version(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].version + mock_val = gcd_version.Version(name='name_value') + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_version_flattened_error_async(): + client = VersionsAsyncClient( + credentials=ga_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_version( + gcd_version.CreateVersionRequest(), + parent='parent_value', + version=gcd_version.Version(name='name_value'), + ) + + +def test_update_version(transport: str = 'grpc', request_type=gcd_version.UpdateVersionRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version( + name='name_value', + description='description_value', + version_number=1518, + status=gcd_version.Version.VersionStatus.IN_PROGRESS, + ) + response = client.update_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.UpdateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_version.Version) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.version_number == 1518 + assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS + + +def test_update_version_from_dict(): + test_update_version(request_type=dict) + + +def test_update_version_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=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_version), + '__call__') as call: + client.update_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.UpdateVersionRequest() + + +@pytest.mark.asyncio +async def test_update_version_async(transport: str = 'grpc_asyncio', request_type=gcd_version.UpdateVersionRequest): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version( + name='name_value', + description='description_value', + version_number=1518, + status=gcd_version.Version.VersionStatus.IN_PROGRESS, + )) + response = await client.update_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.UpdateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_version.Version) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.version_number == 1518 + assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS + + +@pytest.mark.asyncio +async def test_update_version_async_from_dict(): + await test_update_version_async(request_type=dict) + + +def test_update_version_field_headers(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_version.UpdateVersionRequest() + + request.version.name = 'version.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + call.return_value = gcd_version.Version() + client.update_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'version.name=version.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_version_field_headers_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_version.UpdateVersionRequest() + + request.version.name = 'version.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version()) + await client.update_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'version.name=version.name/value', + ) in kw['metadata'] + + +def test_update_version_flattened(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_version( + version=gcd_version.Version(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].version + mock_val = gcd_version.Version(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_version_flattened_error(): + client = VersionsClient( + credentials=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_version( + gcd_version.UpdateVersionRequest(), + version=gcd_version.Version(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_version_flattened_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_version( + version=gcd_version.Version(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].version + mock_val = gcd_version.Version(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_version_flattened_error_async(): + client = VersionsAsyncClient( + credentials=ga_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_version( + gcd_version.UpdateVersionRequest(), + version=gcd_version.Version(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_version(transport: str = 'grpc', request_type=version.DeleteVersionRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == version.DeleteVersionRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_version_from_dict(): + test_delete_version(request_type=dict) + + +def test_delete_version_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=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_version), + '__call__') as call: + client.delete_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == version.DeleteVersionRequest() + + +@pytest.mark.asyncio +async def test_delete_version_async(transport: str = 'grpc_asyncio', request_type=version.DeleteVersionRequest): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == version.DeleteVersionRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_version_async_from_dict(): + await test_delete_version_async(request_type=dict) + + +def test_delete_version_field_headers(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.DeleteVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_version), + '__call__') as call: + call.return_value = None + client.delete_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_version_field_headers_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.DeleteVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_version_flattened(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_version), + '__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_version( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_version_flattened_error(): + client = VersionsClient( + credentials=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_version( + version.DeleteVersionRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_version_flattened_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_version), + '__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_version( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_version_flattened_error_async(): + client = VersionsAsyncClient( + credentials=ga_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_version( + version.DeleteVersionRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VersionsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VersionsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = VersionsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.VersionsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.VersionsGrpcTransport, + transports.VersionsGrpcAsyncIOTransport, +]) +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 = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.VersionsGrpcTransport, + ) + +def test_versions_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.VersionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_versions_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflow_v2beta1.services.versions.transports.VersionsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.VersionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_versions', + 'get_version', + 'create_version', + 'update_version', + 'delete_version', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_versions_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.dialogflow_v2beta1.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VersionsTransport( + 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', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +def test_versions_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.dialogflow_v2beta1.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VersionsTransport() + adc.assert_called_once() + + +def test_versions_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) + VersionsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.VersionsGrpcTransport, + transports.VersionsGrpcAsyncIOTransport, + ], +) +def test_versions_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', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.VersionsGrpcTransport, grpc_helpers), + (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_versions_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport]) +def test_versions_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_versions_host_no_port(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_versions_host_with_port(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:8000' + +def test_versions_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VersionsGrpcTransport( + 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_versions_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VersionsGrpcAsyncIOTransport( + 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.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport]) +def test_versions_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.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport]) +def test_versions_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_version_path(): + project = "squid" + version = "clam" + expected = "projects/{project}/agent/versions/{version}".format(project=project, version=version, ) + actual = VersionsClient.version_path(project, version) + assert expected == actual + + +def test_parse_version_path(): + expected = { + "project": "whelk", + "version": "octopus", + } + path = VersionsClient.version_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_version_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = VersionsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = VersionsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = VersionsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = VersionsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = VersionsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = VersionsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = VersionsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = VersionsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = VersionsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = VersionsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.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.VersionsTransport, '_prep_wrapped_messages') as prep: + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.VersionsTransport, '_prep_wrapped_messages') as prep: + transport_class = VersionsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called()