diff --git a/owl-bot-staging/google-apps-chat/v1/.coveragerc b/owl-bot-staging/google-apps-chat/v1/.coveragerc new file mode 100644 index 000000000000..94d089777c45 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/apps/chat/__init__.py + google/apps/chat/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/google-apps-chat/v1/.flake8 b/owl-bot-staging/google-apps-chat/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-apps-chat/v1/MANIFEST.in b/owl-bot-staging/google-apps-chat/v1/MANIFEST.in new file mode 100644 index 000000000000..7de9678a459d --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/apps/chat *.py +recursive-include google/apps/chat_v1 *.py diff --git a/owl-bot-staging/google-apps-chat/v1/README.rst b/owl-bot-staging/google-apps-chat/v1/README.rst new file mode 100644 index 000000000000..e1d28bad02e8 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Apps Chat 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 Apps Chat API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-apps-chat/v1/docs/_static/custom.css b/owl-bot-staging/google-apps-chat/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-apps-chat/v1/docs/chat_v1/chat_service.rst b/owl-bot-staging/google-apps-chat/v1/docs/chat_v1/chat_service.rst new file mode 100644 index 000000000000..2fc1f0f335d2 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/docs/chat_v1/chat_service.rst @@ -0,0 +1,10 @@ +ChatService +----------------------------- + +.. automodule:: google.apps.chat_v1.services.chat_service + :members: + :inherited-members: + +.. automodule:: google.apps.chat_v1.services.chat_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-apps-chat/v1/docs/chat_v1/services_.rst b/owl-bot-staging/google-apps-chat/v1/docs/chat_v1/services_.rst new file mode 100644 index 000000000000..e59fdb30cdd4 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/docs/chat_v1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Apps Chat v1 API +==================================== +.. toctree:: + :maxdepth: 2 + + chat_service diff --git a/owl-bot-staging/google-apps-chat/v1/docs/chat_v1/types_.rst b/owl-bot-staging/google-apps-chat/v1/docs/chat_v1/types_.rst new file mode 100644 index 000000000000..e786c9b1231a --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/docs/chat_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Apps Chat v1 API +================================= + +.. automodule:: google.apps.chat_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-apps-chat/v1/docs/conf.py b/owl-bot-staging/google-apps-chat/v1/docs/conf.py new file mode 100644 index 000000000000..552c77507d3d --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-apps-chat documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-apps-chat" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = 'en' + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Apps 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-apps-chat-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-apps-chat.tex", + u"google-apps-chat Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-apps-chat", + u"Google Apps Chat Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-apps-chat", + u"google-apps-chat Documentation", + author, + "google-apps-chat", + "GAPIC library for Google Apps Chat API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/google-apps-chat/v1/docs/index.rst b/owl-bot-staging/google-apps-chat/v1/docs/index.rst new file mode 100644 index 000000000000..5f811fbc76c6 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + chat_v1/services + chat_v1/types diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat/__init__.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat/__init__.py new file mode 100644 index 000000000000..738a5b255786 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat/__init__.py @@ -0,0 +1,161 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.apps.chat import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.apps.chat_v1.services.chat_service.client import ChatServiceClient +from google.apps.chat_v1.services.chat_service.async_client import ChatServiceAsyncClient + +from google.apps.chat_v1.types.action_status import ActionStatus +from google.apps.chat_v1.types.annotation import Annotation +from google.apps.chat_v1.types.annotation import DriveLinkData +from google.apps.chat_v1.types.annotation import RichLinkMetadata +from google.apps.chat_v1.types.annotation import SlashCommandMetadata +from google.apps.chat_v1.types.annotation import UserMentionMetadata +from google.apps.chat_v1.types.annotation import AnnotationType +from google.apps.chat_v1.types.attachment import Attachment +from google.apps.chat_v1.types.attachment import AttachmentDataRef +from google.apps.chat_v1.types.attachment import DriveDataRef +from google.apps.chat_v1.types.attachment import GetAttachmentRequest +from google.apps.chat_v1.types.attachment import UploadAttachmentRequest +from google.apps.chat_v1.types.attachment import UploadAttachmentResponse +from google.apps.chat_v1.types.contextual_addon import ContextualAddOnMarkup +from google.apps.chat_v1.types.deletion_metadata import DeletionMetadata +from google.apps.chat_v1.types.group import Group +from google.apps.chat_v1.types.history_state import HistoryState +from google.apps.chat_v1.types.matched_url import MatchedUrl +from google.apps.chat_v1.types.membership import CreateMembershipRequest +from google.apps.chat_v1.types.membership import DeleteMembershipRequest +from google.apps.chat_v1.types.membership import GetMembershipRequest +from google.apps.chat_v1.types.membership import ListMembershipsRequest +from google.apps.chat_v1.types.membership import ListMembershipsResponse +from google.apps.chat_v1.types.membership import Membership +from google.apps.chat_v1.types.membership import UpdateMembershipRequest +from google.apps.chat_v1.types.message import AccessoryWidget +from google.apps.chat_v1.types.message import ActionResponse +from google.apps.chat_v1.types.message import AttachedGif +from google.apps.chat_v1.types.message import CardWithId +from google.apps.chat_v1.types.message import CreateMessageRequest +from google.apps.chat_v1.types.message import DeleteMessageRequest +from google.apps.chat_v1.types.message import Dialog +from google.apps.chat_v1.types.message import DialogAction +from google.apps.chat_v1.types.message import GetMessageRequest +from google.apps.chat_v1.types.message import ListMessagesRequest +from google.apps.chat_v1.types.message import ListMessagesResponse +from google.apps.chat_v1.types.message import Message +from google.apps.chat_v1.types.message import QuotedMessageMetadata +from google.apps.chat_v1.types.message import Thread +from google.apps.chat_v1.types.message import UpdateMessageRequest +from google.apps.chat_v1.types.reaction import CreateReactionRequest +from google.apps.chat_v1.types.reaction import CustomEmoji +from google.apps.chat_v1.types.reaction import DeleteReactionRequest +from google.apps.chat_v1.types.reaction import Emoji +from google.apps.chat_v1.types.reaction import EmojiReactionSummary +from google.apps.chat_v1.types.reaction import ListReactionsRequest +from google.apps.chat_v1.types.reaction import ListReactionsResponse +from google.apps.chat_v1.types.reaction import Reaction +from google.apps.chat_v1.types.slash_command import SlashCommand +from google.apps.chat_v1.types.space import CompleteImportSpaceRequest +from google.apps.chat_v1.types.space import CompleteImportSpaceResponse +from google.apps.chat_v1.types.space import CreateSpaceRequest +from google.apps.chat_v1.types.space import DeleteSpaceRequest +from google.apps.chat_v1.types.space import FindDirectMessageRequest +from google.apps.chat_v1.types.space import GetSpaceRequest +from google.apps.chat_v1.types.space import ListSpacesRequest +from google.apps.chat_v1.types.space import ListSpacesResponse +from google.apps.chat_v1.types.space import Space +from google.apps.chat_v1.types.space import UpdateSpaceRequest +from google.apps.chat_v1.types.space_read_state import GetSpaceReadStateRequest +from google.apps.chat_v1.types.space_read_state import SpaceReadState +from google.apps.chat_v1.types.space_read_state import UpdateSpaceReadStateRequest +from google.apps.chat_v1.types.space_setup import SetUpSpaceRequest +from google.apps.chat_v1.types.thread_read_state import GetThreadReadStateRequest +from google.apps.chat_v1.types.thread_read_state import ThreadReadState +from google.apps.chat_v1.types.user import User +from google.apps.chat_v1.types.widgets import WidgetMarkup + +__all__ = ('ChatServiceClient', + 'ChatServiceAsyncClient', + 'ActionStatus', + 'Annotation', + 'DriveLinkData', + 'RichLinkMetadata', + 'SlashCommandMetadata', + 'UserMentionMetadata', + 'AnnotationType', + 'Attachment', + 'AttachmentDataRef', + 'DriveDataRef', + 'GetAttachmentRequest', + 'UploadAttachmentRequest', + 'UploadAttachmentResponse', + 'ContextualAddOnMarkup', + 'DeletionMetadata', + 'Group', + 'HistoryState', + 'MatchedUrl', + 'CreateMembershipRequest', + 'DeleteMembershipRequest', + 'GetMembershipRequest', + 'ListMembershipsRequest', + 'ListMembershipsResponse', + 'Membership', + 'UpdateMembershipRequest', + 'AccessoryWidget', + 'ActionResponse', + 'AttachedGif', + 'CardWithId', + 'CreateMessageRequest', + 'DeleteMessageRequest', + 'Dialog', + 'DialogAction', + 'GetMessageRequest', + 'ListMessagesRequest', + 'ListMessagesResponse', + 'Message', + 'QuotedMessageMetadata', + 'Thread', + 'UpdateMessageRequest', + 'CreateReactionRequest', + 'CustomEmoji', + 'DeleteReactionRequest', + 'Emoji', + 'EmojiReactionSummary', + 'ListReactionsRequest', + 'ListReactionsResponse', + 'Reaction', + 'SlashCommand', + 'CompleteImportSpaceRequest', + 'CompleteImportSpaceResponse', + 'CreateSpaceRequest', + 'DeleteSpaceRequest', + 'FindDirectMessageRequest', + 'GetSpaceRequest', + 'ListSpacesRequest', + 'ListSpacesResponse', + 'Space', + 'UpdateSpaceRequest', + 'GetSpaceReadStateRequest', + 'SpaceReadState', + 'UpdateSpaceReadStateRequest', + 'SetUpSpaceRequest', + 'GetThreadReadStateRequest', + 'ThreadReadState', + 'User', + 'WidgetMarkup', +) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat/gapic_version.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat/py.typed b/owl-bot-staging/google-apps-chat/v1/google/apps/chat/py.typed new file mode 100644 index 000000000000..dcdf2700193b --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-apps-chat package uses inline types. diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/__init__.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/__init__.py new file mode 100644 index 000000000000..2b9eeef779e2 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/__init__.py @@ -0,0 +1,162 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.apps.chat_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.chat_service import ChatServiceClient +from .services.chat_service import ChatServiceAsyncClient + +from .types.action_status import ActionStatus +from .types.annotation import Annotation +from .types.annotation import DriveLinkData +from .types.annotation import RichLinkMetadata +from .types.annotation import SlashCommandMetadata +from .types.annotation import UserMentionMetadata +from .types.annotation import AnnotationType +from .types.attachment import Attachment +from .types.attachment import AttachmentDataRef +from .types.attachment import DriveDataRef +from .types.attachment import GetAttachmentRequest +from .types.attachment import UploadAttachmentRequest +from .types.attachment import UploadAttachmentResponse +from .types.contextual_addon import ContextualAddOnMarkup +from .types.deletion_metadata import DeletionMetadata +from .types.group import Group +from .types.history_state import HistoryState +from .types.matched_url import MatchedUrl +from .types.membership import CreateMembershipRequest +from .types.membership import DeleteMembershipRequest +from .types.membership import GetMembershipRequest +from .types.membership import ListMembershipsRequest +from .types.membership import ListMembershipsResponse +from .types.membership import Membership +from .types.membership import UpdateMembershipRequest +from .types.message import AccessoryWidget +from .types.message import ActionResponse +from .types.message import AttachedGif +from .types.message import CardWithId +from .types.message import CreateMessageRequest +from .types.message import DeleteMessageRequest +from .types.message import Dialog +from .types.message import DialogAction +from .types.message import GetMessageRequest +from .types.message import ListMessagesRequest +from .types.message import ListMessagesResponse +from .types.message import Message +from .types.message import QuotedMessageMetadata +from .types.message import Thread +from .types.message import UpdateMessageRequest +from .types.reaction import CreateReactionRequest +from .types.reaction import CustomEmoji +from .types.reaction import DeleteReactionRequest +from .types.reaction import Emoji +from .types.reaction import EmojiReactionSummary +from .types.reaction import ListReactionsRequest +from .types.reaction import ListReactionsResponse +from .types.reaction import Reaction +from .types.slash_command import SlashCommand +from .types.space import CompleteImportSpaceRequest +from .types.space import CompleteImportSpaceResponse +from .types.space import CreateSpaceRequest +from .types.space import DeleteSpaceRequest +from .types.space import FindDirectMessageRequest +from .types.space import GetSpaceRequest +from .types.space import ListSpacesRequest +from .types.space import ListSpacesResponse +from .types.space import Space +from .types.space import UpdateSpaceRequest +from .types.space_read_state import GetSpaceReadStateRequest +from .types.space_read_state import SpaceReadState +from .types.space_read_state import UpdateSpaceReadStateRequest +from .types.space_setup import SetUpSpaceRequest +from .types.thread_read_state import GetThreadReadStateRequest +from .types.thread_read_state import ThreadReadState +from .types.user import User +from .types.widgets import WidgetMarkup + +__all__ = ( + 'ChatServiceAsyncClient', +'AccessoryWidget', +'ActionResponse', +'ActionStatus', +'Annotation', +'AnnotationType', +'AttachedGif', +'Attachment', +'AttachmentDataRef', +'CardWithId', +'ChatServiceClient', +'CompleteImportSpaceRequest', +'CompleteImportSpaceResponse', +'ContextualAddOnMarkup', +'CreateMembershipRequest', +'CreateMessageRequest', +'CreateReactionRequest', +'CreateSpaceRequest', +'CustomEmoji', +'DeleteMembershipRequest', +'DeleteMessageRequest', +'DeleteReactionRequest', +'DeleteSpaceRequest', +'DeletionMetadata', +'Dialog', +'DialogAction', +'DriveDataRef', +'DriveLinkData', +'Emoji', +'EmojiReactionSummary', +'FindDirectMessageRequest', +'GetAttachmentRequest', +'GetMembershipRequest', +'GetMessageRequest', +'GetSpaceReadStateRequest', +'GetSpaceRequest', +'GetThreadReadStateRequest', +'Group', +'HistoryState', +'ListMembershipsRequest', +'ListMembershipsResponse', +'ListMessagesRequest', +'ListMessagesResponse', +'ListReactionsRequest', +'ListReactionsResponse', +'ListSpacesRequest', +'ListSpacesResponse', +'MatchedUrl', +'Membership', +'Message', +'QuotedMessageMetadata', +'Reaction', +'RichLinkMetadata', +'SetUpSpaceRequest', +'SlashCommand', +'SlashCommandMetadata', +'Space', +'SpaceReadState', +'Thread', +'ThreadReadState', +'UpdateMembershipRequest', +'UpdateMessageRequest', +'UpdateSpaceReadStateRequest', +'UpdateSpaceRequest', +'UploadAttachmentRequest', +'UploadAttachmentResponse', +'User', +'UserMentionMetadata', +'WidgetMarkup', +) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/gapic_metadata.json b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/gapic_metadata.json new file mode 100644 index 000000000000..5bb370aac865 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/gapic_metadata.json @@ -0,0 +1,418 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.apps.chat_v1", + "protoPackage": "google.chat.v1", + "schema": "1.0", + "services": { + "ChatService": { + "clients": { + "grpc": { + "libraryClient": "ChatServiceClient", + "rpcs": { + "CompleteImportSpace": { + "methods": [ + "complete_import_space" + ] + }, + "CreateMembership": { + "methods": [ + "create_membership" + ] + }, + "CreateMessage": { + "methods": [ + "create_message" + ] + }, + "CreateReaction": { + "methods": [ + "create_reaction" + ] + }, + "CreateSpace": { + "methods": [ + "create_space" + ] + }, + "DeleteMembership": { + "methods": [ + "delete_membership" + ] + }, + "DeleteMessage": { + "methods": [ + "delete_message" + ] + }, + "DeleteReaction": { + "methods": [ + "delete_reaction" + ] + }, + "DeleteSpace": { + "methods": [ + "delete_space" + ] + }, + "FindDirectMessage": { + "methods": [ + "find_direct_message" + ] + }, + "GetAttachment": { + "methods": [ + "get_attachment" + ] + }, + "GetMembership": { + "methods": [ + "get_membership" + ] + }, + "GetMessage": { + "methods": [ + "get_message" + ] + }, + "GetSpace": { + "methods": [ + "get_space" + ] + }, + "GetSpaceReadState": { + "methods": [ + "get_space_read_state" + ] + }, + "GetThreadReadState": { + "methods": [ + "get_thread_read_state" + ] + }, + "ListMemberships": { + "methods": [ + "list_memberships" + ] + }, + "ListMessages": { + "methods": [ + "list_messages" + ] + }, + "ListReactions": { + "methods": [ + "list_reactions" + ] + }, + "ListSpaces": { + "methods": [ + "list_spaces" + ] + }, + "SetUpSpace": { + "methods": [ + "set_up_space" + ] + }, + "UpdateMembership": { + "methods": [ + "update_membership" + ] + }, + "UpdateMessage": { + "methods": [ + "update_message" + ] + }, + "UpdateSpace": { + "methods": [ + "update_space" + ] + }, + "UpdateSpaceReadState": { + "methods": [ + "update_space_read_state" + ] + }, + "UploadAttachment": { + "methods": [ + "upload_attachment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ChatServiceAsyncClient", + "rpcs": { + "CompleteImportSpace": { + "methods": [ + "complete_import_space" + ] + }, + "CreateMembership": { + "methods": [ + "create_membership" + ] + }, + "CreateMessage": { + "methods": [ + "create_message" + ] + }, + "CreateReaction": { + "methods": [ + "create_reaction" + ] + }, + "CreateSpace": { + "methods": [ + "create_space" + ] + }, + "DeleteMembership": { + "methods": [ + "delete_membership" + ] + }, + "DeleteMessage": { + "methods": [ + "delete_message" + ] + }, + "DeleteReaction": { + "methods": [ + "delete_reaction" + ] + }, + "DeleteSpace": { + "methods": [ + "delete_space" + ] + }, + "FindDirectMessage": { + "methods": [ + "find_direct_message" + ] + }, + "GetAttachment": { + "methods": [ + "get_attachment" + ] + }, + "GetMembership": { + "methods": [ + "get_membership" + ] + }, + "GetMessage": { + "methods": [ + "get_message" + ] + }, + "GetSpace": { + "methods": [ + "get_space" + ] + }, + "GetSpaceReadState": { + "methods": [ + "get_space_read_state" + ] + }, + "GetThreadReadState": { + "methods": [ + "get_thread_read_state" + ] + }, + "ListMemberships": { + "methods": [ + "list_memberships" + ] + }, + "ListMessages": { + "methods": [ + "list_messages" + ] + }, + "ListReactions": { + "methods": [ + "list_reactions" + ] + }, + "ListSpaces": { + "methods": [ + "list_spaces" + ] + }, + "SetUpSpace": { + "methods": [ + "set_up_space" + ] + }, + "UpdateMembership": { + "methods": [ + "update_membership" + ] + }, + "UpdateMessage": { + "methods": [ + "update_message" + ] + }, + "UpdateSpace": { + "methods": [ + "update_space" + ] + }, + "UpdateSpaceReadState": { + "methods": [ + "update_space_read_state" + ] + }, + "UploadAttachment": { + "methods": [ + "upload_attachment" + ] + } + } + }, + "rest": { + "libraryClient": "ChatServiceClient", + "rpcs": { + "CompleteImportSpace": { + "methods": [ + "complete_import_space" + ] + }, + "CreateMembership": { + "methods": [ + "create_membership" + ] + }, + "CreateMessage": { + "methods": [ + "create_message" + ] + }, + "CreateReaction": { + "methods": [ + "create_reaction" + ] + }, + "CreateSpace": { + "methods": [ + "create_space" + ] + }, + "DeleteMembership": { + "methods": [ + "delete_membership" + ] + }, + "DeleteMessage": { + "methods": [ + "delete_message" + ] + }, + "DeleteReaction": { + "methods": [ + "delete_reaction" + ] + }, + "DeleteSpace": { + "methods": [ + "delete_space" + ] + }, + "FindDirectMessage": { + "methods": [ + "find_direct_message" + ] + }, + "GetAttachment": { + "methods": [ + "get_attachment" + ] + }, + "GetMembership": { + "methods": [ + "get_membership" + ] + }, + "GetMessage": { + "methods": [ + "get_message" + ] + }, + "GetSpace": { + "methods": [ + "get_space" + ] + }, + "GetSpaceReadState": { + "methods": [ + "get_space_read_state" + ] + }, + "GetThreadReadState": { + "methods": [ + "get_thread_read_state" + ] + }, + "ListMemberships": { + "methods": [ + "list_memberships" + ] + }, + "ListMessages": { + "methods": [ + "list_messages" + ] + }, + "ListReactions": { + "methods": [ + "list_reactions" + ] + }, + "ListSpaces": { + "methods": [ + "list_spaces" + ] + }, + "SetUpSpace": { + "methods": [ + "set_up_space" + ] + }, + "UpdateMembership": { + "methods": [ + "update_membership" + ] + }, + "UpdateMessage": { + "methods": [ + "update_message" + ] + }, + "UpdateSpace": { + "methods": [ + "update_space" + ] + }, + "UpdateSpaceReadState": { + "methods": [ + "update_space_read_state" + ] + }, + "UploadAttachment": { + "methods": [ + "upload_attachment" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/gapic_version.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/py.typed b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/py.typed new file mode 100644 index 000000000000..dcdf2700193b --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-apps-chat package uses inline types. diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/__init__.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/__init__.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/__init__.py new file mode 100644 index 000000000000..adb37fafe3ea --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ChatServiceClient +from .async_client import ChatServiceAsyncClient + +__all__ = ( + 'ChatServiceClient', + 'ChatServiceAsyncClient', +) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/async_client.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/async_client.py new file mode 100644 index 000000000000..abdd00d174cd --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/async_client.py @@ -0,0 +1,3577 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.apps.chat_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.apps.chat_v1.services.chat_service import pagers +from google.apps.chat_v1.types import annotation +from google.apps.chat_v1.types import attachment +from google.apps.chat_v1.types import contextual_addon +from google.apps.chat_v1.types import deletion_metadata +from google.apps.chat_v1.types import group +from google.apps.chat_v1.types import history_state +from google.apps.chat_v1.types import matched_url +from google.apps.chat_v1.types import membership +from google.apps.chat_v1.types import membership as gc_membership +from google.apps.chat_v1.types import message +from google.apps.chat_v1.types import message as gc_message +from google.apps.chat_v1.types import reaction +from google.apps.chat_v1.types import reaction as gc_reaction +from google.apps.chat_v1.types import slash_command +from google.apps.chat_v1.types import space +from google.apps.chat_v1.types import space as gc_space +from google.apps.chat_v1.types import space_read_state +from google.apps.chat_v1.types import space_read_state as gc_space_read_state +from google.apps.chat_v1.types import space_setup +from google.apps.chat_v1.types import thread_read_state +from google.apps.chat_v1.types import user +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ChatServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ChatServiceGrpcAsyncIOTransport +from .client import ChatServiceClient + + +class ChatServiceAsyncClient: + """Enables developers to build Chat apps and + integrations on Google Chat Platform. + """ + + _client: ChatServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = ChatServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ChatServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ChatServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = ChatServiceClient._DEFAULT_UNIVERSE + + attachment_path = staticmethod(ChatServiceClient.attachment_path) + parse_attachment_path = staticmethod(ChatServiceClient.parse_attachment_path) + membership_path = staticmethod(ChatServiceClient.membership_path) + parse_membership_path = staticmethod(ChatServiceClient.parse_membership_path) + message_path = staticmethod(ChatServiceClient.message_path) + parse_message_path = staticmethod(ChatServiceClient.parse_message_path) + quoted_message_metadata_path = staticmethod(ChatServiceClient.quoted_message_metadata_path) + parse_quoted_message_metadata_path = staticmethod(ChatServiceClient.parse_quoted_message_metadata_path) + reaction_path = staticmethod(ChatServiceClient.reaction_path) + parse_reaction_path = staticmethod(ChatServiceClient.parse_reaction_path) + space_path = staticmethod(ChatServiceClient.space_path) + parse_space_path = staticmethod(ChatServiceClient.parse_space_path) + space_read_state_path = staticmethod(ChatServiceClient.space_read_state_path) + parse_space_read_state_path = staticmethod(ChatServiceClient.parse_space_read_state_path) + thread_path = staticmethod(ChatServiceClient.thread_path) + parse_thread_path = staticmethod(ChatServiceClient.parse_thread_path) + thread_read_state_path = staticmethod(ChatServiceClient.thread_read_state_path) + parse_thread_read_state_path = staticmethod(ChatServiceClient.parse_thread_read_state_path) + common_billing_account_path = staticmethod(ChatServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ChatServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ChatServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ChatServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ChatServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ChatServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ChatServiceClient.common_project_path) + parse_common_project_path = staticmethod(ChatServiceClient.parse_common_project_path) + common_location_path = staticmethod(ChatServiceClient.common_location_path) + parse_common_location_path = staticmethod(ChatServiceClient.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: + ChatServiceAsyncClient: The constructed client. + """ + return ChatServiceClient.from_service_account_info.__func__(ChatServiceAsyncClient, 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: + ChatServiceAsyncClient: The constructed client. + """ + return ChatServiceClient.from_service_account_file.__func__(ChatServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return ChatServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ChatServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ChatServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial(type(ChatServiceClient).get_transport_class, type(ChatServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ChatServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the chat service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ChatServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ChatServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_message(self, + request: Optional[Union[gc_message.CreateMessageRequest, dict]] = None, + *, + parent: Optional[str] = None, + message: Optional[gc_message.Message] = None, + message_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_message.Message: + r"""Creates a message in a Google Chat space. For an example, see + `Send a + message `__. + + Calling this method requires + `authentication `__ + and supports the following authentication types: + + - For text messages, user authentication or app authentication + are supported. + - For card messages, only app authentication is supported. + (Only Chat apps can create card messages.) + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_create_message(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.CreateMessageRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_message(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.CreateMessageRequest, dict]]): + The request object. Creates a message. + parent (:class:`str`): + Required. The resource name of the space in which to + create a message. + + Format: ``spaces/{space}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + message (:class:`google.apps.chat_v1.types.Message`): + Required. Message body. + This corresponds to the ``message`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + message_id (:class:`str`): + Optional. A custom ID for a message. Lets Chat apps get, + update, or delete a message without needing to store the + system-assigned ID in the message's resource name + (represented in the message ``name`` field). + + The value for this field must meet the following + requirements: + + - Begins with ``client-``. For example, + ``client-custom-name`` is a valid custom ID, but + ``custom-name`` is not. + - Contains up to 63 characters and only lowercase + letters, numbers, and hyphens. + - Is unique within a space. A Chat app can't use the + same custom ID for different messages. + + For details, see `Name a + message `__. + + This corresponds to the ``message_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.Message: + A message in a Google Chat space. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, message, message_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gc_message.CreateMessageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if message is not None: + request.message = message + if message_id is not None: + request.message_id = message_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_message, + default_retry=retries.AsyncRetry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_messages(self, + request: Optional[Union[message.ListMessagesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListMessagesAsyncPager: + r"""Lists messages in a space that the caller is a member of, + including messages from blocked members and spaces. For an + example, see `List + messages `__. Requires `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_list_messages(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.ListMessagesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_messages(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.ListMessagesRequest, dict]]): + The request object. Lists messages in the specified + space, that the user is a member of. + parent (:class:`str`): + Required. The resource name of the space to list + messages from. + + Format: ``spaces/{space}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.services.chat_service.pagers.ListMessagesAsyncPager: + Response message for listing + messages. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = message.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_retry=retries.AsyncRetry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListMessagesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_memberships(self, + request: Optional[Union[membership.ListMembershipsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListMembershipsAsyncPager: + r"""Lists memberships in a space. For an example, see `List users + and Google Chat apps in a + space `__. + Listing memberships with `app + authentication `__ + lists memberships in spaces that the Chat app has access to, but + excludes Chat app memberships, including its own. Listing + memberships with `User + authentication `__ + lists memberships in spaces that the authenticated user has + access to. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_list_memberships(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.ListMembershipsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_memberships(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.ListMembershipsRequest, dict]]): + The request object. Request message for listing + memberships. + parent (:class:`str`): + Required. The resource name of the + space for which to fetch a membership + list. + + Format: spaces/{space} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.services.chat_service.pagers.ListMembershipsAsyncPager: + Response to list memberships of the + space. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = membership.ListMembershipsRequest(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_memberships, + default_retry=retries.AsyncRetry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListMembershipsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_membership(self, + request: Optional[Union[membership.GetMembershipRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> membership.Membership: + r"""Returns details about a membership. For an example, see `Get + details about a user's or Google Chat app's + membership `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_get_membership(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.GetMembershipRequest( + name="name_value", + ) + + # Make the request + response = await client.get_membership(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.GetMembershipRequest, dict]]): + The request object. Request to get a membership of a + space. + name (:class:`str`): + Required. Resource name of the membership to retrieve. + + To get the app's own membership, you can optionally use + ``spaces/{space}/members/app``. + + Format: ``spaces/{space}/members/{member}`` or + ``spaces/{space}/members/app`` + + When `authenticated as a + user `__, + you can use the user's email as an alias for + ``{member}``. For example, + ``spaces/{space}/members/example@gmail.com`` where + ``example@gmail.com`` is the email of the Google Chat + 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.Membership: + Represents a membership relation in + Google Chat, such as whether a user or + Chat app is invited to, part of, or + absent from a space. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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 = membership.GetMembershipRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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_membership, + default_retry=retries.AsyncRetry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_message(self, + request: Optional[Union[message.GetMessageRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> message.Message: + r"""Returns details about a message. For an example, see `Get + details about a + message `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Note: Might return a message from a blocked member or space. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_get_message(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.GetMessageRequest( + name="name_value", + ) + + # Make the request + response = await client.get_message(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.GetMessageRequest, dict]]): + The request object. Request to get a message. + name (:class:`str`): + Required. Resource name of the message. + + Format: ``spaces/{space}/messages/{message}`` + + If you've set a custom ID for your message, you can use + the value from the ``clientAssignedMessageId`` field for + ``{message}``. For details, see [Name a message] + (https://developers.google.com/workspace/chat/create-messages#name_a_created_message). + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.Message: + A message in a Google Chat space. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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 = message.GetMessageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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_message, + default_retry=retries.AsyncRetry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_message(self, + request: Optional[Union[gc_message.UpdateMessageRequest, dict]] = None, + *, + message: Optional[gc_message.Message] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_message.Message: + r"""Updates a message. There's a difference between the ``patch`` + and ``update`` methods. The ``patch`` method uses a ``patch`` + request while the ``update`` method uses a ``put`` request. We + recommend using the ``patch`` method. For an example, see + `Update a + message `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + When using app authentication, requests can only update messages + created by the calling Chat app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_update_message(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.UpdateMessageRequest( + ) + + # Make the request + response = await client.update_message(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.UpdateMessageRequest, dict]]): + The request object. Request to update a message. + message (:class:`google.apps.chat_v1.types.Message`): + Required. Message with fields + updated. + + This corresponds to the ``message`` 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 field paths to update. Separate multiple + values with commas or use ``*`` to update all field + paths. + + Currently supported field paths: + + - ``text`` + + - ``attachment`` + + - ``cards`` (Requires `app + authentication `__.) + + - ``cards_v2`` (Requires `app + authentication `__.) + + - ``accessory_widgets`` (Requires `app + authentication `__.) + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.Message: + A message in a Google Chat space. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([message, 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 = gc_message.UpdateMessageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if message is not None: + request.message = message + 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_message, + default_retry=retries.AsyncRetry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("message.name", request.message.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_message(self, + request: Optional[Union[message.DeleteMessageRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a message. For an example, see `Delete a + message `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + When using app authentication, requests can only delete messages + created by the calling Chat app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_delete_message(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.DeleteMessageRequest( + name="name_value", + ) + + # Make the request + await client.delete_message(request=request) + + Args: + request (Optional[Union[google.apps.chat_v1.types.DeleteMessageRequest, dict]]): + The request object. Request to delete a message. + name (:class:`str`): + Required. Resource name of the message. + + Format: ``spaces/{space}/messages/{message}`` + + If you've set a custom ID for your message, you can use + the value from the ``clientAssignedMessageId`` field for + ``{message}``. For details, see [Name a message] + (https://developers.google.com/workspace/chat/create-messages#name_a_created_message). + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = message.DeleteMessageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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_message, + default_retry=retries.AsyncRetry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_attachment(self, + request: Optional[Union[attachment.GetAttachmentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> attachment.Attachment: + r"""Gets the metadata of a message attachment. The attachment data + is fetched using the `media + API `__. + For an example, see `Get metadata about a message + attachment `__. + Requires `app + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_get_attachment(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.GetAttachmentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_attachment(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.GetAttachmentRequest, dict]]): + The request object. Request to get an attachment. + name (:class:`str`): + Required. Resource name of the attachment, in the form + ``spaces/*/messages/*/attachments/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.Attachment: + An attachment in Google Chat. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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 = attachment.GetAttachmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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_attachment, + default_retry=retries.AsyncRetry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def upload_attachment(self, + request: Optional[Union[attachment.UploadAttachmentRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> attachment.UploadAttachmentResponse: + r"""Uploads an attachment. For an example, see `Upload media as a + file + attachment `__. + Requires user + `authentication `__. + + You can upload attachments up to 200 MB. Certain file types + aren't supported. For details, see `File types blocked by Google + Chat `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_upload_attachment(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.UploadAttachmentRequest( + parent="parent_value", + filename="filename_value", + ) + + # Make the request + response = await client.upload_attachment(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.UploadAttachmentRequest, dict]]): + The request object. Request to upload an attachment. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.UploadAttachmentResponse: + Response of uploading an attachment. + """ + # Create or coerce a protobuf request object. + request = attachment.UploadAttachmentRequest(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.upload_attachment, + default_retry=retries.AsyncRetry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_spaces(self, + request: Optional[Union[space.ListSpacesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSpacesAsyncPager: + r"""Lists spaces the caller is a member of. Group chats and DMs + aren't listed until the first message is sent. For an example, + see `List + spaces `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Lists spaces visible to the caller or authenticated user. Group + chats and DMs aren't listed until the first message is sent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_list_spaces(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.ListSpacesRequest( + ) + + # Make the request + page_result = client.list_spaces(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.ListSpacesRequest, dict]]): + The request object. A request to list the spaces the + caller is a member of. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.services.chat_service.pagers.ListSpacesAsyncPager: + The response for a list spaces + request. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + request = space.ListSpacesRequest(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_spaces, + default_retry=retries.AsyncRetry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSpacesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_space(self, + request: Optional[Union[space.GetSpaceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> space.Space: + r"""Returns details about a space. For an example, see `Get details + about a + space `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_get_space(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.GetSpaceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_space(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.GetSpaceRequest, dict]]): + The request object. A request to return a single space. + name (:class:`str`): + Required. Resource name of the space, in the form + "spaces/*". + + Format: ``spaces/{space}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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 = space.GetSpaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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_space, + default_retry=retries.AsyncRetry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_space(self, + request: Optional[Union[gc_space.CreateSpaceRequest, dict]] = None, + *, + space: Optional[gc_space.Space] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_space.Space: + r"""Creates a named space. Spaces grouped by topics aren't + supported. For an example, see `Create a + space `__. + + If you receive the error message ``ALREADY_EXISTS`` when + creating a space, try a different ``displayName``. An existing + space within the Google Workspace organization might already use + this display name. + + Requires `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_create_space(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.CreateSpaceRequest( + ) + + # Make the request + response = await client.create_space(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.CreateSpaceRequest, dict]]): + The request object. A request to create a named space. + space (:class:`google.apps.chat_v1.types.Space`): + Required. The ``displayName`` and ``spaceType`` fields + must be populated. Only ``SpaceType.SPACE`` is + supported. + + If you receive the error message ``ALREADY_EXISTS`` when + creating a space, try a different ``displayName``. An + existing space within the Google Workspace organization + might already use this display name. + + The space ``name`` is assigned on the server so anything + specified in this field will be ignored. + + This corresponds to the ``space`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([space]) + if request is 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 = gc_space.CreateSpaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if space is not None: + request.space = space + + # 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_space, + default_retry=retries.AsyncRetry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_up_space(self, + request: Optional[Union[space_setup.SetUpSpaceRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> space.Space: + r"""Creates a space and adds specified users to it. The calling user + is automatically added to the space, and shouldn't be specified + as a membership in the request. For an example, see `Set up a + space with initial + members `__. + + To specify the human members to add, add memberships with the + appropriate ``member.name`` in the ``SetUpSpaceRequest``. To add + a human user, use ``users/{user}``, where ``{user}`` can be the + email address for the user. For users in the same Workspace + organization ``{user}`` can also be the ``id`` for the person + from the People API, or the ``id`` for the user in the Directory + API. For example, if the People API Person profile ID for + ``user@example.com`` is ``123456789``, you can add the user to + the space by setting the ``membership.member.name`` to + ``users/user@example.com`` or ``users/123456789``. + + For a space or group chat, if the caller blocks or is blocked by + some members, then those members aren't added to the created + space. + + To create a direct message (DM) between the calling user and + another human user, specify exactly one membership to represent + the human user. If one user blocks the other, the request fails + and the DM isn't created. + + To create a DM between the calling user and the calling app, set + ``Space.singleUserBotDm`` to ``true`` and don't specify any + memberships. You can only use this method to set up a DM with + the calling app. To add the calling app as a member of a space + or an existing DM between two human users, see `Invite or add a + user or app to a + space `__. + + If a DM already exists between two users, even when one user + blocks the other at the time a request is made, then the + existing DM is returned. + + Spaces with threaded replies aren't supported. If you receive + the error message ``ALREADY_EXISTS`` when setting up a space, + try a different ``displayName``. An existing space within the + Google Workspace organization might already use this display + name. + + Requires `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_set_up_space(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.SetUpSpaceRequest( + ) + + # Make the request + response = await client.set_up_space(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.SetUpSpaceRequest, dict]]): + The request object. Request to create a space and add + specified users to it. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + # Create or coerce a protobuf request object. + request = space_setup.SetUpSpaceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_up_space, + default_retry=retries.AsyncRetry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_space(self, + request: Optional[Union[gc_space.UpdateSpaceRequest, dict]] = None, + *, + space: Optional[gc_space.Space] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_space.Space: + r"""Updates a space. For an example, see `Update a + space `__. + + If you're updating the ``displayName`` field and receive the + error message ``ALREADY_EXISTS``, try a different display name.. + An existing space within the Google Workspace organization might + already use this display name. + + Requires `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_update_space(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.UpdateSpaceRequest( + ) + + # Make the request + response = await client.update_space(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.UpdateSpaceRequest, dict]]): + The request object. A request to update a single space. + space (:class:`google.apps.chat_v1.types.Space`): + Required. Space with fields to be updated. + ``Space.name`` must be populated in the form of + ``spaces/{space}``. Only fields specified by + ``update_mask`` are updated. + + This corresponds to the ``space`` 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 updated field paths, comma separated if + there are multiple. + + Currently supported field paths: + + - ``display_name`` (Only supports changing the display + name of a space with the ``SPACE`` type, or when also + including the ``space_type`` mask to change a + ``GROUP_CHAT`` space type to ``SPACE``. Trying to + update the display name of a ``GROUP_CHAT`` or a + ``DIRECT_MESSAGE`` space results in an invalid + argument error. If you receive the error message + ``ALREADY_EXISTS`` when updating the ``displayName``, + try a different ``displayName``. An existing space + within the Google Workspace organization might + already use this display name.) + + - ``space_type`` (Only supports changing a + ``GROUP_CHAT`` space type to ``SPACE``. Include + ``display_name`` together with ``space_type`` in the + update mask and ensure that the specified space has a + non-empty display name and the ``SPACE`` space type. + Including the ``space_type`` mask and the ``SPACE`` + type in the specified space when updating the display + name is optional if the existing space already has + the ``SPACE`` type. Trying to update the space type + in other ways results in an invalid argument error). + + - ``space_details`` + + - ``space_history_state`` (Supports `turning history on + or off for the + space `__ + if `the organization allows users to change their + history + setting `__. + Warning: mutually exclusive with all other field + paths.) + + - Developer Preview: ``access_settings.audience`` + (Supports changing the `access + setting `__ + of a space. If no audience is specified in the access + setting, the space's access setting is updated to + restricted. Warning: mutually exclusive with all + other field paths.) + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([space, 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 = gc_space.UpdateSpaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if space is not None: + request.space = space + 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_space, + default_retry=retries.AsyncRetry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("space.name", request.space.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_space(self, + request: Optional[Union[space.DeleteSpaceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a named space. Always performs a cascading delete, which + means that the space's child resources—like messages posted in + the space and memberships in the space—are also deleted. For an + example, see `Delete a + space `__. + Requires `user + authentication `__ + from a user who has permission to delete the space. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_delete_space(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.DeleteSpaceRequest( + name="name_value", + ) + + # Make the request + await client.delete_space(request=request) + + Args: + request (Optional[Union[google.apps.chat_v1.types.DeleteSpaceRequest, dict]]): + The request object. Request for deleting a space. + name (:class:`str`): + Required. Resource name of the space to delete. + + Format: ``spaces/{space}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = space.DeleteSpaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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_space, + default_retry=retries.AsyncRetry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def complete_import_space(self, + request: Optional[Union[space.CompleteImportSpaceRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> space.CompleteImportSpaceResponse: + r"""Completes the `import + process `__ + for the specified space and makes it visible to users. Requires + app authentication and domain-wide delegation. For more + information, see `Authorize Google Chat apps to import + data `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_complete_import_space(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.CompleteImportSpaceRequest( + name="name_value", + ) + + # Make the request + response = await client.complete_import_space(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.CompleteImportSpaceRequest, dict]]): + The request object. Request message for completing the + import process for a space. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.CompleteImportSpaceResponse: + Response message for completing the + import process for a space. + + """ + # Create or coerce a protobuf request object. + request = space.CompleteImportSpaceRequest(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.complete_import_space, + default_retry=retries.AsyncRetry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def find_direct_message(self, + request: Optional[Union[space.FindDirectMessageRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> space.Space: + r"""Returns the existing direct message with the specified user. If + no direct message space is found, returns a ``404 NOT_FOUND`` + error. For an example, see `Find a direct + message `__. + + With `user + authentication `__, + returns the direct message space between the specified user and + the authenticated user. + + With `app + authentication `__, + returns the direct message space between the specified user and + the calling Chat app. + + Requires `user + authentication `__ + or `app + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_find_direct_message(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.FindDirectMessageRequest( + name="name_value", + ) + + # Make the request + response = await client.find_direct_message(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.FindDirectMessageRequest, dict]]): + The request object. A request to get direct message space + based on the user resource. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + # Create or coerce a protobuf request object. + request = space.FindDirectMessageRequest(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.find_direct_message, + default_retry=retries.AsyncRetry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_membership(self, + request: Optional[Union[gc_membership.CreateMembershipRequest, dict]] = None, + *, + parent: Optional[str] = None, + membership: Optional[gc_membership.Membership] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_membership.Membership: + r"""Creates a human membership or app membership for the calling + app. Creating memberships for other apps isn't supported. For an + example, see `Invite or add a user or a Google Chat app to a + space `__. + When creating a membership, if the specified member has their + auto-accept policy turned off, then they're invited, and must + accept the space invitation before joining. Otherwise, creating + a membership adds the member directly to the specified space. + Requires `user + authentication `__. + + To specify the member to add, set the ``membership.member.name`` + in the ``CreateMembershipRequest``: + + - To add the calling app to a space or a direct message between + two human users, use ``users/app``. Unable to add other apps + to the space. + + - To add a human user, use ``users/{user}``, where ``{user}`` + can be the email address for the user. For users in the same + Workspace organization ``{user}`` can also be the ``id`` for + the person from the People API, or the ``id`` for the user in + the Directory API. For example, if the People API Person + profile ID for ``user@example.com`` is ``123456789``, you can + add the user to the space by setting the + ``membership.member.name`` to ``users/user@example.com`` or + ``users/123456789``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_create_membership(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.CreateMembershipRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_membership(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.CreateMembershipRequest, dict]]): + The request object. Request message for creating a + membership. + parent (:class:`str`): + Required. The resource name of the + space for which to create the + membership. + + Format: spaces/{space} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + membership (:class:`google.apps.chat_v1.types.Membership`): + Required. The membership relation to create. The + ``memberType`` field must contain a user with the + ``user.name`` and ``user.type`` fields populated. The + server will assign a resource name and overwrite + anything specified. When a Chat app creates a membership + relation for a human user, it must use the + ``chat.memberships`` scope, set ``user.type`` to + ``HUMAN``, and set ``user.name`` with format + ``users/{user}``, where ``{user}`` can be the email + address for the user. For users in the same Workspace + organization ``{user}`` can also be the ``id`` of the + `person `__ + from the People API, or the ``id`` for the user in the + Directory API. For example, if the People API Person + profile ID for ``user@example.com`` is ``123456789``, + you can add the user to the space by setting the + ``membership.member.name`` to ``users/user@example.com`` + or ``users/123456789``. When a Chat app creates a + membership relation for itself, it must use the + ``chat.memberships.app`` scope, set ``user.type`` to + ``BOT``, and set ``user.name`` to ``users/app``. + + This corresponds to the ``membership`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.Membership: + Represents a membership relation in + Google Chat, such as whether a user or + Chat app is invited to, part of, or + absent from a space. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, membership]) + if request is 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 = gc_membership.CreateMembershipRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if membership is not None: + request.membership = membership + + # 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_membership, + default_retry=retries.AsyncRetry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_membership(self, + request: Optional[Union[gc_membership.UpdateMembershipRequest, dict]] = None, + *, + membership: Optional[gc_membership.Membership] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_membership.Membership: + r"""Updates a membership. Requires `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_update_membership(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.UpdateMembershipRequest( + ) + + # Make the request + response = await client.update_membership(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.UpdateMembershipRequest, dict]]): + The request object. Request message for updating a + membership. + membership (:class:`google.apps.chat_v1.types.Membership`): + Required. The membership to update. Only fields + specified by ``update_mask`` are updated. + + This corresponds to the ``membership`` 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 field paths to update. Separate multiple + values with commas or use ``*`` to update all field + paths. + + Currently supported field paths: + + - ``role`` + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.Membership: + Represents a membership relation in + Google Chat, such as whether a user or + Chat app is invited to, part of, or + absent from a space. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([membership, 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 = gc_membership.UpdateMembershipRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if membership is not None: + request.membership = membership + 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_membership, + default_retry=retries.AsyncRetry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("membership.name", request.membership.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_membership(self, + request: Optional[Union[membership.DeleteMembershipRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> membership.Membership: + r"""Deletes a membership. For an example, see `Remove a user or a + Google Chat app from a + space `__. + + Requires `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_delete_membership(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.DeleteMembershipRequest( + name="name_value", + ) + + # Make the request + response = await client.delete_membership(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.DeleteMembershipRequest, dict]]): + The request object. Request to delete a membership in a + space. + name (:class:`str`): + Required. Resource name of the membership to delete. + Chat apps can delete human users' or their own + memberships. Chat apps can't delete other apps' + memberships. + + When deleting a human membership, requires the + ``chat.memberships`` scope and + ``spaces/{space}/members/{member}`` format. You can use + the email as an alias for ``{member}``. For example, + ``spaces/{space}/members/example@gmail.com`` where + ``example@gmail.com`` is the email of the Google Chat + user. + + When deleting an app membership, requires the + ``chat.memberships.app`` scope and + ``spaces/{space}/members/app`` format. + + Format: ``spaces/{space}/members/{member}`` or + ``spaces/{space}/members/app``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.Membership: + Represents a membership relation in + Google Chat, such as whether a user or + Chat app is invited to, part of, or + absent from a space. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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 = membership.DeleteMembershipRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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_membership, + default_retry=retries.AsyncRetry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_reaction(self, + request: Optional[Union[gc_reaction.CreateReactionRequest, dict]] = None, + *, + parent: Optional[str] = None, + reaction: Optional[gc_reaction.Reaction] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_reaction.Reaction: + r"""Creates a reaction and adds it to a message. Only unicode emojis + are supported. For an example, see `Add a reaction to a + message `__. + Requires `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_create_reaction(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.CreateReactionRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_reaction(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.CreateReactionRequest, dict]]): + The request object. Creates a reaction to a message. + parent (:class:`str`): + Required. The message where the reaction is created. + + Format: ``spaces/{space}/messages/{message}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reaction (:class:`google.apps.chat_v1.types.Reaction`): + Required. The reaction to create. + This corresponds to the ``reaction`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.Reaction: + A reaction to a message. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, reaction]) + if request is 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 = gc_reaction.CreateReactionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if reaction is not None: + request.reaction = reaction + + # 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_reaction, + default_retry=retries.AsyncRetry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_reactions(self, + request: Optional[Union[reaction.ListReactionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListReactionsAsyncPager: + r"""Lists reactions to a message. For an example, see `List + reactions for a + message `__. + Requires `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_list_reactions(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.ListReactionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_reactions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.ListReactionsRequest, dict]]): + The request object. Lists reactions to a message. + parent (:class:`str`): + Required. The message users reacted to. + + Format: ``spaces/{space}/messages/{message}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.services.chat_service.pagers.ListReactionsAsyncPager: + Response to a list reactions request. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = reaction.ListReactionsRequest(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_reactions, + default_retry=retries.AsyncRetry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListReactionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_reaction(self, + request: Optional[Union[reaction.DeleteReactionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a reaction to a message. Only unicode emojis are + supported. For an example, see `Delete a + reaction `__. + Requires `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_delete_reaction(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.DeleteReactionRequest( + name="name_value", + ) + + # Make the request + await client.delete_reaction(request=request) + + Args: + request (Optional[Union[google.apps.chat_v1.types.DeleteReactionRequest, dict]]): + The request object. Deletes a reaction to a message. + name (:class:`str`): + Required. Name of the reaction to delete. + + Format: + ``spaces/{space}/messages/{message}/reactions/{reaction}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = reaction.DeleteReactionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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_reaction, + default_retry=retries.AsyncRetry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_space_read_state(self, + request: Optional[Union[space_read_state.GetSpaceReadStateRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> space_read_state.SpaceReadState: + r"""Returns details about a user's read state within a space, used + to identify read and unread messages. + + Requires `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_get_space_read_state(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.GetSpaceReadStateRequest( + name="name_value", + ) + + # Make the request + response = await client.get_space_read_state(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.GetSpaceReadStateRequest, dict]]): + The request object. Request message for GetSpaceReadState + API. + name (:class:`str`): + Required. Resource name of the space read state to + retrieve. + + Only supports getting read state for the calling user. + + To refer to the calling user, set one of the following: + + - The ``me`` alias. For example, + ``users/me/spaces/{space}/spaceReadState``. + + - Their Workspace email address. For example, + ``users/user@example.com/spaces/{space}/spaceReadState``. + + - Their user id. For example, + ``users/123456789/spaces/{space}/spaceReadState``. + + Format: users/{user}/spaces/{space}/spaceReadState + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.SpaceReadState: + A user's read state within a space, + used to identify read and unread + messages. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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 = space_read_state.GetSpaceReadStateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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_space_read_state, + default_retry=retries.AsyncRetry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_space_read_state(self, + request: Optional[Union[gc_space_read_state.UpdateSpaceReadStateRequest, dict]] = None, + *, + space_read_state: Optional[gc_space_read_state.SpaceReadState] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_space_read_state.SpaceReadState: + r"""Updates a user's read state within a space, used to identify + read and unread messages. + + Requires `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_update_space_read_state(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.UpdateSpaceReadStateRequest( + ) + + # Make the request + response = await client.update_space_read_state(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.UpdateSpaceReadStateRequest, dict]]): + The request object. Request message for + UpdateSpaceReadState API. + space_read_state (:class:`google.apps.chat_v1.types.SpaceReadState`): + Required. The space read state and fields to update. + + Only supports updating read state for the calling user. + + To refer to the calling user, set one of the following: + + - The ``me`` alias. For example, + ``users/me/spaces/{space}/spaceReadState``. + + - Their Workspace email address. For example, + ``users/user@example.com/spaces/{space}/spaceReadState``. + + - Their user id. For example, + ``users/123456789/spaces/{space}/spaceReadState``. + + Format: users/{user}/spaces/{space}/spaceReadState + + This corresponds to the ``space_read_state`` 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 field paths to update. Currently supported + field paths: + + - ``last_read_time`` + + When the ``last_read_time`` is before the latest message + create time, the space appears as unread in the UI. + + To mark the space as read, set ``last_read_time`` to any + value later (larger) than the latest message create + time. The ``last_read_time`` is coerced to match the + latest message create time. Note that the space read + state only affects the read state of messages that are + visible in the space's top-level conversation. Replies + in threads are unaffected by this timestamp, and instead + rely on the thread read state. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.SpaceReadState: + A user's read state within a space, + used to identify read and unread + messages. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([space_read_state, 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 = gc_space_read_state.UpdateSpaceReadStateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if space_read_state is not None: + request.space_read_state = space_read_state + 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_space_read_state, + default_retry=retries.AsyncRetry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("space_read_state.name", request.space_read_state.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_thread_read_state(self, + request: Optional[Union[thread_read_state.GetThreadReadStateRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> thread_read_state.ThreadReadState: + r"""Returns details about a user's read state within a thread, used + to identify read and unread messages. + + Requires `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_get_thread_read_state(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.GetThreadReadStateRequest( + name="name_value", + ) + + # Make the request + response = await client.get_thread_read_state(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.GetThreadReadStateRequest, dict]]): + The request object. Request message for + GetThreadReadStateRequest API. + name (:class:`str`): + Required. Resource name of the thread read state to + retrieve. + + Only supports getting read state for the calling user. + + To refer to the calling user, set one of the following: + + - The ``me`` alias. For example, + ``users/me/spaces/{space}/threads/{thread}/threadReadState``. + + - Their Workspace email address. For example, + ``users/user@example.com/spaces/{space}/threads/{thread}/threadReadState``. + + - Their user id. For example, + ``users/123456789/spaces/{space}/threads/{thread}/threadReadState``. + + Format: + users/{user}/spaces/{space}/threads/{thread}/threadReadState + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.ThreadReadState: + A user's read state within a thread, + used to identify read and unread + messages. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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 = thread_read_state.GetThreadReadStateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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_thread_read_state, + default_retry=retries.AsyncRetry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "ChatServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "ChatServiceAsyncClient", +) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/client.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/client.py new file mode 100644 index 000000000000..b96af7a497e2 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/client.py @@ -0,0 +1,3850 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.apps.chat_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.apps.chat_v1.services.chat_service import pagers +from google.apps.chat_v1.types import annotation +from google.apps.chat_v1.types import attachment +from google.apps.chat_v1.types import contextual_addon +from google.apps.chat_v1.types import deletion_metadata +from google.apps.chat_v1.types import group +from google.apps.chat_v1.types import history_state +from google.apps.chat_v1.types import matched_url +from google.apps.chat_v1.types import membership +from google.apps.chat_v1.types import membership as gc_membership +from google.apps.chat_v1.types import message +from google.apps.chat_v1.types import message as gc_message +from google.apps.chat_v1.types import reaction +from google.apps.chat_v1.types import reaction as gc_reaction +from google.apps.chat_v1.types import slash_command +from google.apps.chat_v1.types import space +from google.apps.chat_v1.types import space as gc_space +from google.apps.chat_v1.types import space_read_state +from google.apps.chat_v1.types import space_read_state as gc_space_read_state +from google.apps.chat_v1.types import space_setup +from google.apps.chat_v1.types import thread_read_state +from google.apps.chat_v1.types import user +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ChatServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ChatServiceGrpcTransport +from .transports.grpc_asyncio import ChatServiceGrpcAsyncIOTransport +from .transports.rest import ChatServiceRestTransport + + +class ChatServiceClientMeta(type): + """Metaclass for the ChatService 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[ChatServiceTransport]] + _transport_registry["grpc"] = ChatServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ChatServiceGrpcAsyncIOTransport + _transport_registry["rest"] = ChatServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ChatServiceTransport]: + """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 ChatServiceClient(metaclass=ChatServiceClientMeta): + """Enables developers to build Chat apps and + integrations on Google Chat Platform. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "chat.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "chat.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ChatServiceClient: 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: + ChatServiceClient: 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) -> ChatServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ChatServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def attachment_path(space: str,message: str,attachment: str,) -> str: + """Returns a fully-qualified attachment string.""" + return "spaces/{space}/messages/{message}/attachments/{attachment}".format(space=space, message=message, attachment=attachment, ) + + @staticmethod + def parse_attachment_path(path: str) -> Dict[str,str]: + """Parses a attachment path into its component segments.""" + m = re.match(r"^spaces/(?P.+?)/messages/(?P.+?)/attachments/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def membership_path(space: str,member: str,) -> str: + """Returns a fully-qualified membership string.""" + return "spaces/{space}/members/{member}".format(space=space, member=member, ) + + @staticmethod + def parse_membership_path(path: str) -> Dict[str,str]: + """Parses a membership path into its component segments.""" + m = re.match(r"^spaces/(?P.+?)/members/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def message_path(space: str,message: str,) -> str: + """Returns a fully-qualified message string.""" + return "spaces/{space}/messages/{message}".format(space=space, message=message, ) + + @staticmethod + def parse_message_path(path: str) -> Dict[str,str]: + """Parses a message path into its component segments.""" + m = re.match(r"^spaces/(?P.+?)/messages/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def quoted_message_metadata_path(space: str,message: str,quoted_message_metadata: str,) -> str: + """Returns a fully-qualified quoted_message_metadata string.""" + return "spaces/{space}/messages/{message}/quotedMessageMetadata/{quoted_message_metadata}".format(space=space, message=message, quoted_message_metadata=quoted_message_metadata, ) + + @staticmethod + def parse_quoted_message_metadata_path(path: str) -> Dict[str,str]: + """Parses a quoted_message_metadata path into its component segments.""" + m = re.match(r"^spaces/(?P.+?)/messages/(?P.+?)/quotedMessageMetadata/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def reaction_path(space: str,message: str,reaction: str,) -> str: + """Returns a fully-qualified reaction string.""" + return "spaces/{space}/messages/{message}/reactions/{reaction}".format(space=space, message=message, reaction=reaction, ) + + @staticmethod + def parse_reaction_path(path: str) -> Dict[str,str]: + """Parses a reaction path into its component segments.""" + m = re.match(r"^spaces/(?P.+?)/messages/(?P.+?)/reactions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def space_path(space: str,) -> str: + """Returns a fully-qualified space string.""" + return "spaces/{space}".format(space=space, ) + + @staticmethod + def parse_space_path(path: str) -> Dict[str,str]: + """Parses a space path into its component segments.""" + m = re.match(r"^spaces/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def space_read_state_path(user: str,space: str,) -> str: + """Returns a fully-qualified space_read_state string.""" + return "users/{user}/spaces/{space}/spaceReadState".format(user=user, space=space, ) + + @staticmethod + def parse_space_read_state_path(path: str) -> Dict[str,str]: + """Parses a space_read_state path into its component segments.""" + m = re.match(r"^users/(?P.+?)/spaces/(?P.+?)/spaceReadState$", path) + return m.groupdict() if m else {} + + @staticmethod + def thread_path(space: str,thread: str,) -> str: + """Returns a fully-qualified thread string.""" + return "spaces/{space}/threads/{thread}".format(space=space, thread=thread, ) + + @staticmethod + def parse_thread_path(path: str) -> Dict[str,str]: + """Parses a thread path into its component segments.""" + m = re.match(r"^spaces/(?P.+?)/threads/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def thread_read_state_path(user: str,space: str,thread: str,) -> str: + """Returns a fully-qualified thread_read_state string.""" + return "users/{user}/spaces/{space}/threads/{thread}/threadReadState".format(user=user, space=space, thread=thread, ) + + @staticmethod + def parse_thread_read_state_path(path: str) -> Dict[str,str]: + """Parses a thread_read_state path into its component segments.""" + m = re.match(r"^users/(?P.+?)/spaces/(?P.+?)/threads/(?P.+?)/threadReadState$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = ChatServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = ChatServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ChatServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = ChatServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = ChatServiceClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + ChatServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ChatServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the chat service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ChatServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ChatServiceClient._read_environment_variables() + self._client_cert_source = ChatServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = ChatServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, ChatServiceTransport) + if transport_provided: + # transport is a ChatServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(ChatServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + ChatServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(cast(str, transport)) + self._transport = Transport( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def create_message(self, + request: Optional[Union[gc_message.CreateMessageRequest, dict]] = None, + *, + parent: Optional[str] = None, + message: Optional[gc_message.Message] = None, + message_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_message.Message: + r"""Creates a message in a Google Chat space. For an example, see + `Send a + message `__. + + Calling this method requires + `authentication `__ + and supports the following authentication types: + + - For text messages, user authentication or app authentication + are supported. + - For card messages, only app authentication is supported. + (Only Chat apps can create card messages.) + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_create_message(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.CreateMessageRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_message(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.CreateMessageRequest, dict]): + The request object. Creates a message. + parent (str): + Required. The resource name of the space in which to + create a message. + + Format: ``spaces/{space}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + message (google.apps.chat_v1.types.Message): + Required. Message body. + This corresponds to the ``message`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + message_id (str): + Optional. A custom ID for a message. Lets Chat apps get, + update, or delete a message without needing to store the + system-assigned ID in the message's resource name + (represented in the message ``name`` field). + + The value for this field must meet the following + requirements: + + - Begins with ``client-``. For example, + ``client-custom-name`` is a valid custom ID, but + ``custom-name`` is not. + - Contains up to 63 characters and only lowercase + letters, numbers, and hyphens. + - Is unique within a space. A Chat app can't use the + same custom ID for different messages. + + For details, see `Name a + message `__. + + This corresponds to the ``message_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.Message: + A message in a Google Chat space. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, message, message_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gc_message.CreateMessageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gc_message.CreateMessageRequest): + request = gc_message.CreateMessageRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if message is not None: + request.message = message + if message_id is not None: + request.message_id = message_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_message] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_messages(self, + request: Optional[Union[message.ListMessagesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListMessagesPager: + r"""Lists messages in a space that the caller is a member of, + including messages from blocked members and spaces. For an + example, see `List + messages `__. Requires `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_list_messages(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.ListMessagesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_messages(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.apps.chat_v1.types.ListMessagesRequest, dict]): + The request object. Lists messages in the specified + space, that the user is a member of. + parent (str): + Required. The resource name of the space to list + messages from. + + Format: ``spaces/{space}`` + + 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.apps.chat_v1.services.chat_service.pagers.ListMessagesPager: + Response message for listing + messages. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a message.ListMessagesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, message.ListMessagesRequest): + request = message.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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListMessagesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_memberships(self, + request: Optional[Union[membership.ListMembershipsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListMembershipsPager: + r"""Lists memberships in a space. For an example, see `List users + and Google Chat apps in a + space `__. + Listing memberships with `app + authentication `__ + lists memberships in spaces that the Chat app has access to, but + excludes Chat app memberships, including its own. Listing + memberships with `User + authentication `__ + lists memberships in spaces that the authenticated user has + access to. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_list_memberships(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.ListMembershipsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_memberships(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.apps.chat_v1.types.ListMembershipsRequest, dict]): + The request object. Request message for listing + memberships. + parent (str): + Required. The resource name of the + space for which to fetch a membership + list. + + Format: spaces/{space} + + 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.apps.chat_v1.services.chat_service.pagers.ListMembershipsPager: + Response to list memberships of the + space. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a membership.ListMembershipsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, membership.ListMembershipsRequest): + request = membership.ListMembershipsRequest(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_memberships] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListMembershipsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_membership(self, + request: Optional[Union[membership.GetMembershipRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> membership.Membership: + r"""Returns details about a membership. For an example, see `Get + details about a user's or Google Chat app's + membership `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_get_membership(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.GetMembershipRequest( + name="name_value", + ) + + # Make the request + response = client.get_membership(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.GetMembershipRequest, dict]): + The request object. Request to get a membership of a + space. + name (str): + Required. Resource name of the membership to retrieve. + + To get the app's own membership, you can optionally use + ``spaces/{space}/members/app``. + + Format: ``spaces/{space}/members/{member}`` or + ``spaces/{space}/members/app`` + + When `authenticated as a + user `__, + you can use the user's email as an alias for + ``{member}``. For example, + ``spaces/{space}/members/example@gmail.com`` where + ``example@gmail.com`` is the email of the Google Chat + 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.apps.chat_v1.types.Membership: + Represents a membership relation in + Google Chat, such as whether a user or + Chat app is invited to, part of, or + absent from a space. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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 membership.GetMembershipRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, membership.GetMembershipRequest): + request = membership.GetMembershipRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_membership] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_message(self, + request: Optional[Union[message.GetMessageRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> message.Message: + r"""Returns details about a message. For an example, see `Get + details about a + message `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Note: Might return a message from a blocked member or space. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_get_message(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.GetMessageRequest( + name="name_value", + ) + + # Make the request + response = client.get_message(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.GetMessageRequest, dict]): + The request object. Request to get a message. + name (str): + Required. Resource name of the message. + + Format: ``spaces/{space}/messages/{message}`` + + If you've set a custom ID for your message, you can use + the value from the ``clientAssignedMessageId`` field for + ``{message}``. For details, see [Name a message] + (https://developers.google.com/workspace/chat/create-messages#name_a_created_message). + + 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.apps.chat_v1.types.Message: + A message in a Google Chat space. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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 message.GetMessageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, message.GetMessageRequest): + request = message.GetMessageRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_message] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_message(self, + request: Optional[Union[gc_message.UpdateMessageRequest, dict]] = None, + *, + message: Optional[gc_message.Message] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_message.Message: + r"""Updates a message. There's a difference between the ``patch`` + and ``update`` methods. The ``patch`` method uses a ``patch`` + request while the ``update`` method uses a ``put`` request. We + recommend using the ``patch`` method. For an example, see + `Update a + message `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + When using app authentication, requests can only update messages + created by the calling Chat app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_update_message(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.UpdateMessageRequest( + ) + + # Make the request + response = client.update_message(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.UpdateMessageRequest, dict]): + The request object. Request to update a message. + message (google.apps.chat_v1.types.Message): + Required. Message with fields + updated. + + This corresponds to the ``message`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The field paths to update. Separate multiple + values with commas or use ``*`` to update all field + paths. + + Currently supported field paths: + + - ``text`` + + - ``attachment`` + + - ``cards`` (Requires `app + authentication `__.) + + - ``cards_v2`` (Requires `app + authentication `__.) + + - ``accessory_widgets`` (Requires `app + authentication `__.) + + 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.apps.chat_v1.types.Message: + A message in a Google Chat space. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([message, 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 gc_message.UpdateMessageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gc_message.UpdateMessageRequest): + request = gc_message.UpdateMessageRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if message is not None: + request.message = message + 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_message] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("message.name", request.message.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_message(self, + request: Optional[Union[message.DeleteMessageRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a message. For an example, see `Delete a + message `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + When using app authentication, requests can only delete messages + created by the calling Chat app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_delete_message(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.DeleteMessageRequest( + name="name_value", + ) + + # Make the request + client.delete_message(request=request) + + Args: + request (Union[google.apps.chat_v1.types.DeleteMessageRequest, dict]): + The request object. Request to delete a message. + name (str): + Required. Resource name of the message. + + Format: ``spaces/{space}/messages/{message}`` + + If you've set a custom ID for your message, you can use + the value from the ``clientAssignedMessageId`` field for + ``{message}``. For details, see [Name a message] + (https://developers.google.com/workspace/chat/create-messages#name_a_created_message). + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a message.DeleteMessageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, message.DeleteMessageRequest): + request = message.DeleteMessageRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_message] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_attachment(self, + request: Optional[Union[attachment.GetAttachmentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> attachment.Attachment: + r"""Gets the metadata of a message attachment. The attachment data + is fetched using the `media + API `__. + For an example, see `Get metadata about a message + attachment `__. + Requires `app + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_get_attachment(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.GetAttachmentRequest( + name="name_value", + ) + + # Make the request + response = client.get_attachment(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.GetAttachmentRequest, dict]): + The request object. Request to get an attachment. + name (str): + Required. Resource name of the attachment, in the form + ``spaces/*/messages/*/attachments/*``. + + 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.apps.chat_v1.types.Attachment: + An attachment in Google Chat. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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 attachment.GetAttachmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, attachment.GetAttachmentRequest): + request = attachment.GetAttachmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_attachment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def upload_attachment(self, + request: Optional[Union[attachment.UploadAttachmentRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> attachment.UploadAttachmentResponse: + r"""Uploads an attachment. For an example, see `Upload media as a + file + attachment `__. + Requires user + `authentication `__. + + You can upload attachments up to 200 MB. Certain file types + aren't supported. For details, see `File types blocked by Google + Chat `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_upload_attachment(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.UploadAttachmentRequest( + parent="parent_value", + filename="filename_value", + ) + + # Make the request + response = client.upload_attachment(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.UploadAttachmentRequest, dict]): + The request object. Request to upload an attachment. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.UploadAttachmentResponse: + Response of uploading an attachment. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a attachment.UploadAttachmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, attachment.UploadAttachmentRequest): + request = attachment.UploadAttachmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.upload_attachment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_spaces(self, + request: Optional[Union[space.ListSpacesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSpacesPager: + r"""Lists spaces the caller is a member of. Group chats and DMs + aren't listed until the first message is sent. For an example, + see `List + spaces `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Lists spaces visible to the caller or authenticated user. Group + chats and DMs aren't listed until the first message is sent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_list_spaces(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.ListSpacesRequest( + ) + + # Make the request + page_result = client.list_spaces(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.apps.chat_v1.types.ListSpacesRequest, dict]): + The request object. A request to list the spaces the + caller is a member of. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.services.chat_service.pagers.ListSpacesPager: + The response for a list spaces + request. + 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 space.ListSpacesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, space.ListSpacesRequest): + request = space.ListSpacesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_spaces] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSpacesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_space(self, + request: Optional[Union[space.GetSpaceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> space.Space: + r"""Returns details about a space. For an example, see `Get details + about a + space `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_get_space(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.GetSpaceRequest( + name="name_value", + ) + + # Make the request + response = client.get_space(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.GetSpaceRequest, dict]): + The request object. A request to return a single space. + name (str): + Required. Resource name of the space, in the form + "spaces/*". + + Format: ``spaces/{space}`` + + 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.apps.chat_v1.types.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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 space.GetSpaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, space.GetSpaceRequest): + request = space.GetSpaceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_space] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_space(self, + request: Optional[Union[gc_space.CreateSpaceRequest, dict]] = None, + *, + space: Optional[gc_space.Space] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_space.Space: + r"""Creates a named space. Spaces grouped by topics aren't + supported. For an example, see `Create a + space `__. + + If you receive the error message ``ALREADY_EXISTS`` when + creating a space, try a different ``displayName``. An existing + space within the Google Workspace organization might already use + this display name. + + Requires `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_create_space(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.CreateSpaceRequest( + ) + + # Make the request + response = client.create_space(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.CreateSpaceRequest, dict]): + The request object. A request to create a named space. + space (google.apps.chat_v1.types.Space): + Required. The ``displayName`` and ``spaceType`` fields + must be populated. Only ``SpaceType.SPACE`` is + supported. + + If you receive the error message ``ALREADY_EXISTS`` when + creating a space, try a different ``displayName``. An + existing space within the Google Workspace organization + might already use this display name. + + The space ``name`` is assigned on the server so anything + specified in this field will be ignored. + + This corresponds to the ``space`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([space]) + if request is 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 gc_space.CreateSpaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gc_space.CreateSpaceRequest): + request = gc_space.CreateSpaceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if space is not None: + request.space = space + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_space] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_up_space(self, + request: Optional[Union[space_setup.SetUpSpaceRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> space.Space: + r"""Creates a space and adds specified users to it. The calling user + is automatically added to the space, and shouldn't be specified + as a membership in the request. For an example, see `Set up a + space with initial + members `__. + + To specify the human members to add, add memberships with the + appropriate ``member.name`` in the ``SetUpSpaceRequest``. To add + a human user, use ``users/{user}``, where ``{user}`` can be the + email address for the user. For users in the same Workspace + organization ``{user}`` can also be the ``id`` for the person + from the People API, or the ``id`` for the user in the Directory + API. For example, if the People API Person profile ID for + ``user@example.com`` is ``123456789``, you can add the user to + the space by setting the ``membership.member.name`` to + ``users/user@example.com`` or ``users/123456789``. + + For a space or group chat, if the caller blocks or is blocked by + some members, then those members aren't added to the created + space. + + To create a direct message (DM) between the calling user and + another human user, specify exactly one membership to represent + the human user. If one user blocks the other, the request fails + and the DM isn't created. + + To create a DM between the calling user and the calling app, set + ``Space.singleUserBotDm`` to ``true`` and don't specify any + memberships. You can only use this method to set up a DM with + the calling app. To add the calling app as a member of a space + or an existing DM between two human users, see `Invite or add a + user or app to a + space `__. + + If a DM already exists between two users, even when one user + blocks the other at the time a request is made, then the + existing DM is returned. + + Spaces with threaded replies aren't supported. If you receive + the error message ``ALREADY_EXISTS`` when setting up a space, + try a different ``displayName``. An existing space within the + Google Workspace organization might already use this display + name. + + Requires `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_set_up_space(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.SetUpSpaceRequest( + ) + + # Make the request + response = client.set_up_space(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.SetUpSpaceRequest, dict]): + The request object. Request to create a space and add + specified users to it. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a space_setup.SetUpSpaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, space_setup.SetUpSpaceRequest): + request = space_setup.SetUpSpaceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_up_space] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_space(self, + request: Optional[Union[gc_space.UpdateSpaceRequest, dict]] = None, + *, + space: Optional[gc_space.Space] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_space.Space: + r"""Updates a space. For an example, see `Update a + space `__. + + If you're updating the ``displayName`` field and receive the + error message ``ALREADY_EXISTS``, try a different display name.. + An existing space within the Google Workspace organization might + already use this display name. + + Requires `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_update_space(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.UpdateSpaceRequest( + ) + + # Make the request + response = client.update_space(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.UpdateSpaceRequest, dict]): + The request object. A request to update a single space. + space (google.apps.chat_v1.types.Space): + Required. Space with fields to be updated. + ``Space.name`` must be populated in the form of + ``spaces/{space}``. Only fields specified by + ``update_mask`` are updated. + + This corresponds to the ``space`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The updated field paths, comma separated if + there are multiple. + + Currently supported field paths: + + - ``display_name`` (Only supports changing the display + name of a space with the ``SPACE`` type, or when also + including the ``space_type`` mask to change a + ``GROUP_CHAT`` space type to ``SPACE``. Trying to + update the display name of a ``GROUP_CHAT`` or a + ``DIRECT_MESSAGE`` space results in an invalid + argument error. If you receive the error message + ``ALREADY_EXISTS`` when updating the ``displayName``, + try a different ``displayName``. An existing space + within the Google Workspace organization might + already use this display name.) + + - ``space_type`` (Only supports changing a + ``GROUP_CHAT`` space type to ``SPACE``. Include + ``display_name`` together with ``space_type`` in the + update mask and ensure that the specified space has a + non-empty display name and the ``SPACE`` space type. + Including the ``space_type`` mask and the ``SPACE`` + type in the specified space when updating the display + name is optional if the existing space already has + the ``SPACE`` type. Trying to update the space type + in other ways results in an invalid argument error). + + - ``space_details`` + + - ``space_history_state`` (Supports `turning history on + or off for the + space `__ + if `the organization allows users to change their + history + setting `__. + Warning: mutually exclusive with all other field + paths.) + + - Developer Preview: ``access_settings.audience`` + (Supports changing the `access + setting `__ + of a space. If no audience is specified in the access + setting, the space's access setting is updated to + restricted. Warning: mutually exclusive with all + other field paths.) + + 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.apps.chat_v1.types.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([space, 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 gc_space.UpdateSpaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gc_space.UpdateSpaceRequest): + request = gc_space.UpdateSpaceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if space is not None: + request.space = space + 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_space] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("space.name", request.space.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_space(self, + request: Optional[Union[space.DeleteSpaceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a named space. Always performs a cascading delete, which + means that the space's child resources—like messages posted in + the space and memberships in the space—are also deleted. For an + example, see `Delete a + space `__. + Requires `user + authentication `__ + from a user who has permission to delete the space. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_delete_space(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.DeleteSpaceRequest( + name="name_value", + ) + + # Make the request + client.delete_space(request=request) + + Args: + request (Union[google.apps.chat_v1.types.DeleteSpaceRequest, dict]): + The request object. Request for deleting a space. + name (str): + Required. Resource name of the space to delete. + + Format: ``spaces/{space}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a space.DeleteSpaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, space.DeleteSpaceRequest): + request = space.DeleteSpaceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_space] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def complete_import_space(self, + request: Optional[Union[space.CompleteImportSpaceRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> space.CompleteImportSpaceResponse: + r"""Completes the `import + process `__ + for the specified space and makes it visible to users. Requires + app authentication and domain-wide delegation. For more + information, see `Authorize Google Chat apps to import + data `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_complete_import_space(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.CompleteImportSpaceRequest( + name="name_value", + ) + + # Make the request + response = client.complete_import_space(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.CompleteImportSpaceRequest, dict]): + The request object. Request message for completing the + import process for a space. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.CompleteImportSpaceResponse: + Response message for completing the + import process for a space. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a space.CompleteImportSpaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, space.CompleteImportSpaceRequest): + request = space.CompleteImportSpaceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.complete_import_space] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def find_direct_message(self, + request: Optional[Union[space.FindDirectMessageRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> space.Space: + r"""Returns the existing direct message with the specified user. If + no direct message space is found, returns a ``404 NOT_FOUND`` + error. For an example, see `Find a direct + message `__. + + With `user + authentication `__, + returns the direct message space between the specified user and + the authenticated user. + + With `app + authentication `__, + returns the direct message space between the specified user and + the calling Chat app. + + Requires `user + authentication `__ + or `app + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_find_direct_message(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.FindDirectMessageRequest( + name="name_value", + ) + + # Make the request + response = client.find_direct_message(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.FindDirectMessageRequest, dict]): + The request object. A request to get direct message space + based on the user resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a space.FindDirectMessageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, space.FindDirectMessageRequest): + request = space.FindDirectMessageRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.find_direct_message] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_membership(self, + request: Optional[Union[gc_membership.CreateMembershipRequest, dict]] = None, + *, + parent: Optional[str] = None, + membership: Optional[gc_membership.Membership] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_membership.Membership: + r"""Creates a human membership or app membership for the calling + app. Creating memberships for other apps isn't supported. For an + example, see `Invite or add a user or a Google Chat app to a + space `__. + When creating a membership, if the specified member has their + auto-accept policy turned off, then they're invited, and must + accept the space invitation before joining. Otherwise, creating + a membership adds the member directly to the specified space. + Requires `user + authentication `__. + + To specify the member to add, set the ``membership.member.name`` + in the ``CreateMembershipRequest``: + + - To add the calling app to a space or a direct message between + two human users, use ``users/app``. Unable to add other apps + to the space. + + - To add a human user, use ``users/{user}``, where ``{user}`` + can be the email address for the user. For users in the same + Workspace organization ``{user}`` can also be the ``id`` for + the person from the People API, or the ``id`` for the user in + the Directory API. For example, if the People API Person + profile ID for ``user@example.com`` is ``123456789``, you can + add the user to the space by setting the + ``membership.member.name`` to ``users/user@example.com`` or + ``users/123456789``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_create_membership(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.CreateMembershipRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_membership(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.CreateMembershipRequest, dict]): + The request object. Request message for creating a + membership. + parent (str): + Required. The resource name of the + space for which to create the + membership. + + Format: spaces/{space} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + membership (google.apps.chat_v1.types.Membership): + Required. The membership relation to create. The + ``memberType`` field must contain a user with the + ``user.name`` and ``user.type`` fields populated. The + server will assign a resource name and overwrite + anything specified. When a Chat app creates a membership + relation for a human user, it must use the + ``chat.memberships`` scope, set ``user.type`` to + ``HUMAN``, and set ``user.name`` with format + ``users/{user}``, where ``{user}`` can be the email + address for the user. For users in the same Workspace + organization ``{user}`` can also be the ``id`` of the + `person `__ + from the People API, or the ``id`` for the user in the + Directory API. For example, if the People API Person + profile ID for ``user@example.com`` is ``123456789``, + you can add the user to the space by setting the + ``membership.member.name`` to ``users/user@example.com`` + or ``users/123456789``. When a Chat app creates a + membership relation for itself, it must use the + ``chat.memberships.app`` scope, set ``user.type`` to + ``BOT``, and set ``user.name`` to ``users/app``. + + This corresponds to the ``membership`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.Membership: + Represents a membership relation in + Google Chat, such as whether a user or + Chat app is invited to, part of, or + absent from a space. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, membership]) + if request is 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 gc_membership.CreateMembershipRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gc_membership.CreateMembershipRequest): + request = gc_membership.CreateMembershipRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if membership is not None: + request.membership = membership + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_membership] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_membership(self, + request: Optional[Union[gc_membership.UpdateMembershipRequest, dict]] = None, + *, + membership: Optional[gc_membership.Membership] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_membership.Membership: + r"""Updates a membership. Requires `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_update_membership(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.UpdateMembershipRequest( + ) + + # Make the request + response = client.update_membership(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.UpdateMembershipRequest, dict]): + The request object. Request message for updating a + membership. + membership (google.apps.chat_v1.types.Membership): + Required. The membership to update. Only fields + specified by ``update_mask`` are updated. + + This corresponds to the ``membership`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The field paths to update. Separate multiple + values with commas or use ``*`` to update all field + paths. + + Currently supported field paths: + + - ``role`` + + 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.apps.chat_v1.types.Membership: + Represents a membership relation in + Google Chat, such as whether a user or + Chat app is invited to, part of, or + absent from a space. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([membership, 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 gc_membership.UpdateMembershipRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gc_membership.UpdateMembershipRequest): + request = gc_membership.UpdateMembershipRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if membership is not None: + request.membership = membership + 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_membership] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("membership.name", request.membership.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_membership(self, + request: Optional[Union[membership.DeleteMembershipRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> membership.Membership: + r"""Deletes a membership. For an example, see `Remove a user or a + Google Chat app from a + space `__. + + Requires `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_delete_membership(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.DeleteMembershipRequest( + name="name_value", + ) + + # Make the request + response = client.delete_membership(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.DeleteMembershipRequest, dict]): + The request object. Request to delete a membership in a + space. + name (str): + Required. Resource name of the membership to delete. + Chat apps can delete human users' or their own + memberships. Chat apps can't delete other apps' + memberships. + + When deleting a human membership, requires the + ``chat.memberships`` scope and + ``spaces/{space}/members/{member}`` format. You can use + the email as an alias for ``{member}``. For example, + ``spaces/{space}/members/example@gmail.com`` where + ``example@gmail.com`` is the email of the Google Chat + user. + + When deleting an app membership, requires the + ``chat.memberships.app`` scope and + ``spaces/{space}/members/app`` format. + + Format: ``spaces/{space}/members/{member}`` or + ``spaces/{space}/members/app``. + + 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.apps.chat_v1.types.Membership: + Represents a membership relation in + Google Chat, such as whether a user or + Chat app is invited to, part of, or + absent from a space. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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 membership.DeleteMembershipRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, membership.DeleteMembershipRequest): + request = membership.DeleteMembershipRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_membership] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_reaction(self, + request: Optional[Union[gc_reaction.CreateReactionRequest, dict]] = None, + *, + parent: Optional[str] = None, + reaction: Optional[gc_reaction.Reaction] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_reaction.Reaction: + r"""Creates a reaction and adds it to a message. Only unicode emojis + are supported. For an example, see `Add a reaction to a + message `__. + Requires `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_create_reaction(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.CreateReactionRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_reaction(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.CreateReactionRequest, dict]): + The request object. Creates a reaction to a message. + parent (str): + Required. The message where the reaction is created. + + Format: ``spaces/{space}/messages/{message}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reaction (google.apps.chat_v1.types.Reaction): + Required. The reaction to create. + This corresponds to the ``reaction`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.apps.chat_v1.types.Reaction: + A reaction to a message. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, reaction]) + if request is 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 gc_reaction.CreateReactionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gc_reaction.CreateReactionRequest): + request = gc_reaction.CreateReactionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if reaction is not None: + request.reaction = reaction + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_reaction] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_reactions(self, + request: Optional[Union[reaction.ListReactionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListReactionsPager: + r"""Lists reactions to a message. For an example, see `List + reactions for a + message `__. + Requires `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_list_reactions(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.ListReactionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_reactions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.apps.chat_v1.types.ListReactionsRequest, dict]): + The request object. Lists reactions to a message. + parent (str): + Required. The message users reacted to. + + Format: ``spaces/{space}/messages/{message}`` + + 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.apps.chat_v1.services.chat_service.pagers.ListReactionsPager: + Response to a list reactions request. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a reaction.ListReactionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, reaction.ListReactionsRequest): + request = reaction.ListReactionsRequest(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_reactions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListReactionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_reaction(self, + request: Optional[Union[reaction.DeleteReactionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a reaction to a message. Only unicode emojis are + supported. For an example, see `Delete a + reaction `__. + Requires `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_delete_reaction(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.DeleteReactionRequest( + name="name_value", + ) + + # Make the request + client.delete_reaction(request=request) + + Args: + request (Union[google.apps.chat_v1.types.DeleteReactionRequest, dict]): + The request object. Deletes a reaction to a message. + name (str): + Required. Name of the reaction to delete. + + Format: + ``spaces/{space}/messages/{message}/reactions/{reaction}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a reaction.DeleteReactionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, reaction.DeleteReactionRequest): + request = reaction.DeleteReactionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_reaction] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_space_read_state(self, + request: Optional[Union[space_read_state.GetSpaceReadStateRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> space_read_state.SpaceReadState: + r"""Returns details about a user's read state within a space, used + to identify read and unread messages. + + Requires `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_get_space_read_state(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.GetSpaceReadStateRequest( + name="name_value", + ) + + # Make the request + response = client.get_space_read_state(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.GetSpaceReadStateRequest, dict]): + The request object. Request message for GetSpaceReadState + API. + name (str): + Required. Resource name of the space read state to + retrieve. + + Only supports getting read state for the calling user. + + To refer to the calling user, set one of the following: + + - The ``me`` alias. For example, + ``users/me/spaces/{space}/spaceReadState``. + + - Their Workspace email address. For example, + ``users/user@example.com/spaces/{space}/spaceReadState``. + + - Their user id. For example, + ``users/123456789/spaces/{space}/spaceReadState``. + + Format: users/{user}/spaces/{space}/spaceReadState + + 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.apps.chat_v1.types.SpaceReadState: + A user's read state within a space, + used to identify read and unread + messages. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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 space_read_state.GetSpaceReadStateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, space_read_state.GetSpaceReadStateRequest): + request = space_read_state.GetSpaceReadStateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_space_read_state] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_space_read_state(self, + request: Optional[Union[gc_space_read_state.UpdateSpaceReadStateRequest, dict]] = None, + *, + space_read_state: Optional[gc_space_read_state.SpaceReadState] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_space_read_state.SpaceReadState: + r"""Updates a user's read state within a space, used to identify + read and unread messages. + + Requires `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_update_space_read_state(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.UpdateSpaceReadStateRequest( + ) + + # Make the request + response = client.update_space_read_state(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.UpdateSpaceReadStateRequest, dict]): + The request object. Request message for + UpdateSpaceReadState API. + space_read_state (google.apps.chat_v1.types.SpaceReadState): + Required. The space read state and fields to update. + + Only supports updating read state for the calling user. + + To refer to the calling user, set one of the following: + + - The ``me`` alias. For example, + ``users/me/spaces/{space}/spaceReadState``. + + - Their Workspace email address. For example, + ``users/user@example.com/spaces/{space}/spaceReadState``. + + - Their user id. For example, + ``users/123456789/spaces/{space}/spaceReadState``. + + Format: users/{user}/spaces/{space}/spaceReadState + + This corresponds to the ``space_read_state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The field paths to update. Currently supported + field paths: + + - ``last_read_time`` + + When the ``last_read_time`` is before the latest message + create time, the space appears as unread in the UI. + + To mark the space as read, set ``last_read_time`` to any + value later (larger) than the latest message create + time. The ``last_read_time`` is coerced to match the + latest message create time. Note that the space read + state only affects the read state of messages that are + visible in the space's top-level conversation. Replies + in threads are unaffected by this timestamp, and instead + rely on the thread read state. + + 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.apps.chat_v1.types.SpaceReadState: + A user's read state within a space, + used to identify read and unread + messages. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([space_read_state, 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 gc_space_read_state.UpdateSpaceReadStateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gc_space_read_state.UpdateSpaceReadStateRequest): + request = gc_space_read_state.UpdateSpaceReadStateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if space_read_state is not None: + request.space_read_state = space_read_state + 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_space_read_state] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("space_read_state.name", request.space_read_state.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_thread_read_state(self, + request: Optional[Union[thread_read_state.GetThreadReadStateRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> thread_read_state.ThreadReadState: + r"""Returns details about a user's read state within a thread, used + to identify read and unread messages. + + Requires `user + authentication `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_get_thread_read_state(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.GetThreadReadStateRequest( + name="name_value", + ) + + # Make the request + response = client.get_thread_read_state(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.GetThreadReadStateRequest, dict]): + The request object. Request message for + GetThreadReadStateRequest API. + name (str): + Required. Resource name of the thread read state to + retrieve. + + Only supports getting read state for the calling user. + + To refer to the calling user, set one of the following: + + - The ``me`` alias. For example, + ``users/me/spaces/{space}/threads/{thread}/threadReadState``. + + - Their Workspace email address. For example, + ``users/user@example.com/spaces/{space}/threads/{thread}/threadReadState``. + + - Their user id. For example, + ``users/123456789/spaces/{space}/threads/{thread}/threadReadState``. + + Format: + users/{user}/spaces/{space}/threads/{thread}/threadReadState + + 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.apps.chat_v1.types.ThreadReadState: + A user's read state within a thread, + used to identify read and unread + messages. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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 thread_read_state.GetThreadReadStateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, thread_read_state.GetThreadReadStateRequest): + request = thread_read_state.GetThreadReadStateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_thread_read_state] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ChatServiceClient": + 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() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "ChatServiceClient", +) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/pagers.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/pagers.py new file mode 100644 index 000000000000..9742fbabab18 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/pagers.py @@ -0,0 +1,505 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.apps.chat_v1.types import membership +from google.apps.chat_v1.types import message +from google.apps.chat_v1.types import reaction +from google.apps.chat_v1.types import space + + +class ListMessagesPager: + """A pager for iterating through ``list_messages`` requests. + + This class thinly wraps an initial + :class:`google.apps.chat_v1.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.apps.chat_v1.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[..., message.ListMessagesResponse], + request: message.ListMessagesRequest, + response: message.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.apps.chat_v1.types.ListMessagesRequest): + The initial request object. + response (google.apps.chat_v1.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 = message.ListMessagesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[message.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[message.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.apps.chat_v1.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.apps.chat_v1.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[message.ListMessagesResponse]], + request: message.ListMessagesRequest, + response: message.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.apps.chat_v1.types.ListMessagesRequest): + The initial request object. + response (google.apps.chat_v1.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 = message.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[message.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[message.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) + + +class ListMembershipsPager: + """A pager for iterating through ``list_memberships`` requests. + + This class thinly wraps an initial + :class:`google.apps.chat_v1.types.ListMembershipsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``memberships`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMemberships`` requests and continue to iterate + through the ``memberships`` field on the + corresponding responses. + + All the usual :class:`google.apps.chat_v1.types.ListMembershipsResponse` + 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[..., membership.ListMembershipsResponse], + request: membership.ListMembershipsRequest, + response: membership.ListMembershipsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.apps.chat_v1.types.ListMembershipsRequest): + The initial request object. + response (google.apps.chat_v1.types.ListMembershipsResponse): + 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 = membership.ListMembershipsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[membership.ListMembershipsResponse]: + 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[membership.Membership]: + for page in self.pages: + yield from page.memberships + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMembershipsAsyncPager: + """A pager for iterating through ``list_memberships`` requests. + + This class thinly wraps an initial + :class:`google.apps.chat_v1.types.ListMembershipsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``memberships`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMemberships`` requests and continue to iterate + through the ``memberships`` field on the + corresponding responses. + + All the usual :class:`google.apps.chat_v1.types.ListMembershipsResponse` + 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[membership.ListMembershipsResponse]], + request: membership.ListMembershipsRequest, + response: membership.ListMembershipsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.apps.chat_v1.types.ListMembershipsRequest): + The initial request object. + response (google.apps.chat_v1.types.ListMembershipsResponse): + 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 = membership.ListMembershipsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[membership.ListMembershipsResponse]: + 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[membership.Membership]: + async def async_generator(): + async for page in self.pages: + for response in page.memberships: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSpacesPager: + """A pager for iterating through ``list_spaces`` requests. + + This class thinly wraps an initial + :class:`google.apps.chat_v1.types.ListSpacesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``spaces`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSpaces`` requests and continue to iterate + through the ``spaces`` field on the + corresponding responses. + + All the usual :class:`google.apps.chat_v1.types.ListSpacesResponse` + 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[..., space.ListSpacesResponse], + request: space.ListSpacesRequest, + response: space.ListSpacesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.apps.chat_v1.types.ListSpacesRequest): + The initial request object. + response (google.apps.chat_v1.types.ListSpacesResponse): + 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 = space.ListSpacesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[space.ListSpacesResponse]: + 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[space.Space]: + for page in self.pages: + yield from page.spaces + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSpacesAsyncPager: + """A pager for iterating through ``list_spaces`` requests. + + This class thinly wraps an initial + :class:`google.apps.chat_v1.types.ListSpacesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``spaces`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSpaces`` requests and continue to iterate + through the ``spaces`` field on the + corresponding responses. + + All the usual :class:`google.apps.chat_v1.types.ListSpacesResponse` + 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[space.ListSpacesResponse]], + request: space.ListSpacesRequest, + response: space.ListSpacesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.apps.chat_v1.types.ListSpacesRequest): + The initial request object. + response (google.apps.chat_v1.types.ListSpacesResponse): + 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 = space.ListSpacesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[space.ListSpacesResponse]: + 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[space.Space]: + async def async_generator(): + async for page in self.pages: + for response in page.spaces: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListReactionsPager: + """A pager for iterating through ``list_reactions`` requests. + + This class thinly wraps an initial + :class:`google.apps.chat_v1.types.ListReactionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``reactions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListReactions`` requests and continue to iterate + through the ``reactions`` field on the + corresponding responses. + + All the usual :class:`google.apps.chat_v1.types.ListReactionsResponse` + 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[..., reaction.ListReactionsResponse], + request: reaction.ListReactionsRequest, + response: reaction.ListReactionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.apps.chat_v1.types.ListReactionsRequest): + The initial request object. + response (google.apps.chat_v1.types.ListReactionsResponse): + 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 = reaction.ListReactionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[reaction.ListReactionsResponse]: + 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[reaction.Reaction]: + for page in self.pages: + yield from page.reactions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListReactionsAsyncPager: + """A pager for iterating through ``list_reactions`` requests. + + This class thinly wraps an initial + :class:`google.apps.chat_v1.types.ListReactionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``reactions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListReactions`` requests and continue to iterate + through the ``reactions`` field on the + corresponding responses. + + All the usual :class:`google.apps.chat_v1.types.ListReactionsResponse` + 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[reaction.ListReactionsResponse]], + request: reaction.ListReactionsRequest, + response: reaction.ListReactionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.apps.chat_v1.types.ListReactionsRequest): + The initial request object. + response (google.apps.chat_v1.types.ListReactionsResponse): + 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 = reaction.ListReactionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[reaction.ListReactionsResponse]: + 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[reaction.Reaction]: + async def async_generator(): + async for page in self.pages: + for response in page.reactions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/transports/__init__.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/transports/__init__.py new file mode 100644 index 000000000000..9f56aeaaa7f8 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import ChatServiceTransport +from .grpc import ChatServiceGrpcTransport +from .grpc_asyncio import ChatServiceGrpcAsyncIOTransport +from .rest import ChatServiceRestTransport +from .rest import ChatServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ChatServiceTransport]] +_transport_registry['grpc'] = ChatServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ChatServiceGrpcAsyncIOTransport +_transport_registry['rest'] = ChatServiceRestTransport + +__all__ = ( + 'ChatServiceTransport', + 'ChatServiceGrpcTransport', + 'ChatServiceGrpcAsyncIOTransport', + 'ChatServiceRestTransport', + 'ChatServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/transports/base.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/transports/base.py new file mode 100644 index 000000000000..d5d5706fd9b0 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/transports/base.py @@ -0,0 +1,687 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.apps.chat_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.apps.chat_v1.types import attachment +from google.apps.chat_v1.types import membership +from google.apps.chat_v1.types import membership as gc_membership +from google.apps.chat_v1.types import message +from google.apps.chat_v1.types import message as gc_message +from google.apps.chat_v1.types import reaction +from google.apps.chat_v1.types import reaction as gc_reaction +from google.apps.chat_v1.types import space +from google.apps.chat_v1.types import space as gc_space +from google.apps.chat_v1.types import space_read_state +from google.apps.chat_v1.types import space_read_state as gc_space_read_state +from google.apps.chat_v1.types import space_setup +from google.apps.chat_v1.types import thread_read_state +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class ChatServiceTransport(abc.ABC): + """Abstract transport class for ChatService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/chat.bot', + 'https://www.googleapis.com/auth/chat.delete', + 'https://www.googleapis.com/auth/chat.import', + 'https://www.googleapis.com/auth/chat.memberships', + 'https://www.googleapis.com/auth/chat.memberships.app', + 'https://www.googleapis.com/auth/chat.memberships.readonly', + 'https://www.googleapis.com/auth/chat.messages', + 'https://www.googleapis.com/auth/chat.messages.create', + 'https://www.googleapis.com/auth/chat.messages.reactions', + 'https://www.googleapis.com/auth/chat.messages.reactions.create', + 'https://www.googleapis.com/auth/chat.messages.reactions.readonly', + 'https://www.googleapis.com/auth/chat.messages.readonly', + 'https://www.googleapis.com/auth/chat.spaces', + 'https://www.googleapis.com/auth/chat.spaces.create', + 'https://www.googleapis.com/auth/chat.spaces.readonly', + 'https://www.googleapis.com/auth/chat.users.readstate', + 'https://www.googleapis.com/auth/chat.users.readstate.readonly', + ) + + DEFAULT_HOST: str = 'chat.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'chat.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_message: gapic_v1.method.wrap_method( + self.create_message, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_messages: gapic_v1.method.wrap_method( + self.list_messages, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_memberships: gapic_v1.method.wrap_method( + self.list_memberships, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.get_membership: gapic_v1.method.wrap_method( + self.get_membership, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.get_message: gapic_v1.method.wrap_method( + self.get_message, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.update_message: gapic_v1.method.wrap_method( + self.update_message, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.delete_message: gapic_v1.method.wrap_method( + self.delete_message, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.get_attachment: gapic_v1.method.wrap_method( + self.get_attachment, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.upload_attachment: gapic_v1.method.wrap_method( + self.upload_attachment, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_spaces: gapic_v1.method.wrap_method( + self.list_spaces, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.get_space: gapic_v1.method.wrap_method( + self.get_space, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.create_space: gapic_v1.method.wrap_method( + self.create_space, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.set_up_space: gapic_v1.method.wrap_method( + self.set_up_space, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.update_space: gapic_v1.method.wrap_method( + self.update_space, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.delete_space: gapic_v1.method.wrap_method( + self.delete_space, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.complete_import_space: gapic_v1.method.wrap_method( + self.complete_import_space, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.find_direct_message: gapic_v1.method.wrap_method( + self.find_direct_message, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.create_membership: gapic_v1.method.wrap_method( + self.create_membership, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.update_membership: gapic_v1.method.wrap_method( + self.update_membership, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.delete_membership: gapic_v1.method.wrap_method( + self.delete_membership, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.create_reaction: gapic_v1.method.wrap_method( + self.create_reaction, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_reactions: gapic_v1.method.wrap_method( + self.list_reactions, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.delete_reaction: gapic_v1.method.wrap_method( + self.delete_reaction, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.get_space_read_state: gapic_v1.method.wrap_method( + self.get_space_read_state, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.update_space_read_state: gapic_v1.method.wrap_method( + self.update_space_read_state, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.get_thread_read_state: gapic_v1.method.wrap_method( + self.get_thread_read_state, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.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 create_message(self) -> Callable[ + [gc_message.CreateMessageRequest], + Union[ + gc_message.Message, + Awaitable[gc_message.Message] + ]]: + raise NotImplementedError() + + @property + def list_messages(self) -> Callable[ + [message.ListMessagesRequest], + Union[ + message.ListMessagesResponse, + Awaitable[message.ListMessagesResponse] + ]]: + raise NotImplementedError() + + @property + def list_memberships(self) -> Callable[ + [membership.ListMembershipsRequest], + Union[ + membership.ListMembershipsResponse, + Awaitable[membership.ListMembershipsResponse] + ]]: + raise NotImplementedError() + + @property + def get_membership(self) -> Callable[ + [membership.GetMembershipRequest], + Union[ + membership.Membership, + Awaitable[membership.Membership] + ]]: + raise NotImplementedError() + + @property + def get_message(self) -> Callable[ + [message.GetMessageRequest], + Union[ + message.Message, + Awaitable[message.Message] + ]]: + raise NotImplementedError() + + @property + def update_message(self) -> Callable[ + [gc_message.UpdateMessageRequest], + Union[ + gc_message.Message, + Awaitable[gc_message.Message] + ]]: + raise NotImplementedError() + + @property + def delete_message(self) -> Callable[ + [message.DeleteMessageRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_attachment(self) -> Callable[ + [attachment.GetAttachmentRequest], + Union[ + attachment.Attachment, + Awaitable[attachment.Attachment] + ]]: + raise NotImplementedError() + + @property + def upload_attachment(self) -> Callable[ + [attachment.UploadAttachmentRequest], + Union[ + attachment.UploadAttachmentResponse, + Awaitable[attachment.UploadAttachmentResponse] + ]]: + raise NotImplementedError() + + @property + def list_spaces(self) -> Callable[ + [space.ListSpacesRequest], + Union[ + space.ListSpacesResponse, + Awaitable[space.ListSpacesResponse] + ]]: + raise NotImplementedError() + + @property + def get_space(self) -> Callable[ + [space.GetSpaceRequest], + Union[ + space.Space, + Awaitable[space.Space] + ]]: + raise NotImplementedError() + + @property + def create_space(self) -> Callable[ + [gc_space.CreateSpaceRequest], + Union[ + gc_space.Space, + Awaitable[gc_space.Space] + ]]: + raise NotImplementedError() + + @property + def set_up_space(self) -> Callable[ + [space_setup.SetUpSpaceRequest], + Union[ + space.Space, + Awaitable[space.Space] + ]]: + raise NotImplementedError() + + @property + def update_space(self) -> Callable[ + [gc_space.UpdateSpaceRequest], + Union[ + gc_space.Space, + Awaitable[gc_space.Space] + ]]: + raise NotImplementedError() + + @property + def delete_space(self) -> Callable[ + [space.DeleteSpaceRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def complete_import_space(self) -> Callable[ + [space.CompleteImportSpaceRequest], + Union[ + space.CompleteImportSpaceResponse, + Awaitable[space.CompleteImportSpaceResponse] + ]]: + raise NotImplementedError() + + @property + def find_direct_message(self) -> Callable[ + [space.FindDirectMessageRequest], + Union[ + space.Space, + Awaitable[space.Space] + ]]: + raise NotImplementedError() + + @property + def create_membership(self) -> Callable[ + [gc_membership.CreateMembershipRequest], + Union[ + gc_membership.Membership, + Awaitable[gc_membership.Membership] + ]]: + raise NotImplementedError() + + @property + def update_membership(self) -> Callable[ + [gc_membership.UpdateMembershipRequest], + Union[ + gc_membership.Membership, + Awaitable[gc_membership.Membership] + ]]: + raise NotImplementedError() + + @property + def delete_membership(self) -> Callable[ + [membership.DeleteMembershipRequest], + Union[ + membership.Membership, + Awaitable[membership.Membership] + ]]: + raise NotImplementedError() + + @property + def create_reaction(self) -> Callable[ + [gc_reaction.CreateReactionRequest], + Union[ + gc_reaction.Reaction, + Awaitable[gc_reaction.Reaction] + ]]: + raise NotImplementedError() + + @property + def list_reactions(self) -> Callable[ + [reaction.ListReactionsRequest], + Union[ + reaction.ListReactionsResponse, + Awaitable[reaction.ListReactionsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_reaction(self) -> Callable[ + [reaction.DeleteReactionRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_space_read_state(self) -> Callable[ + [space_read_state.GetSpaceReadStateRequest], + Union[ + space_read_state.SpaceReadState, + Awaitable[space_read_state.SpaceReadState] + ]]: + raise NotImplementedError() + + @property + def update_space_read_state(self) -> Callable[ + [gc_space_read_state.UpdateSpaceReadStateRequest], + Union[ + gc_space_read_state.SpaceReadState, + Awaitable[gc_space_read_state.SpaceReadState] + ]]: + raise NotImplementedError() + + @property + def get_thread_read_state(self) -> Callable[ + [thread_read_state.GetThreadReadStateRequest], + Union[ + thread_read_state.ThreadReadState, + Awaitable[thread_read_state.ThreadReadState] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ChatServiceTransport', +) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/transports/grpc.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/transports/grpc.py new file mode 100644 index 000000000000..64c07f577994 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/transports/grpc.py @@ -0,0 +1,1190 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.apps.chat_v1.types import attachment +from google.apps.chat_v1.types import membership +from google.apps.chat_v1.types import membership as gc_membership +from google.apps.chat_v1.types import message +from google.apps.chat_v1.types import message as gc_message +from google.apps.chat_v1.types import reaction +from google.apps.chat_v1.types import reaction as gc_reaction +from google.apps.chat_v1.types import space +from google.apps.chat_v1.types import space as gc_space +from google.apps.chat_v1.types import space_read_state +from google.apps.chat_v1.types import space_read_state as gc_space_read_state +from google.apps.chat_v1.types import space_setup +from google.apps.chat_v1.types import thread_read_state +from google.protobuf import empty_pb2 # type: ignore +from .base import ChatServiceTransport, DEFAULT_CLIENT_INFO + + +class ChatServiceGrpcTransport(ChatServiceTransport): + """gRPC backend transport for ChatService. + + Enables developers to build Chat apps and + integrations on Google Chat Platform. + + 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 = 'chat.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'chat.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``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, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'chat.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def create_message(self) -> Callable[ + [gc_message.CreateMessageRequest], + gc_message.Message]: + r"""Return a callable for the create message method over gRPC. + + Creates a message in a Google Chat space. For an example, see + `Send a + message `__. + + Calling this method requires + `authentication `__ + and supports the following authentication types: + + - For text messages, user authentication or app authentication + are supported. + - For card messages, only app authentication is supported. + (Only Chat apps can create card messages.) + + Returns: + Callable[[~.CreateMessageRequest], + ~.Message]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_message' not in self._stubs: + self._stubs['create_message'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/CreateMessage', + request_serializer=gc_message.CreateMessageRequest.serialize, + response_deserializer=gc_message.Message.deserialize, + ) + return self._stubs['create_message'] + + @property + def list_messages(self) -> Callable[ + [message.ListMessagesRequest], + message.ListMessagesResponse]: + r"""Return a callable for the list messages method over gRPC. + + Lists messages in a space that the caller is a member of, + including messages from blocked members and spaces. For an + example, see `List + messages `__. Requires `user + authentication `__. + + 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.chat.v1.ChatService/ListMessages', + request_serializer=message.ListMessagesRequest.serialize, + response_deserializer=message.ListMessagesResponse.deserialize, + ) + return self._stubs['list_messages'] + + @property + def list_memberships(self) -> Callable[ + [membership.ListMembershipsRequest], + membership.ListMembershipsResponse]: + r"""Return a callable for the list memberships method over gRPC. + + Lists memberships in a space. For an example, see `List users + and Google Chat apps in a + space `__. + Listing memberships with `app + authentication `__ + lists memberships in spaces that the Chat app has access to, but + excludes Chat app memberships, including its own. Listing + memberships with `User + authentication `__ + lists memberships in spaces that the authenticated user has + access to. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Returns: + Callable[[~.ListMembershipsRequest], + ~.ListMembershipsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_memberships' not in self._stubs: + self._stubs['list_memberships'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/ListMemberships', + request_serializer=membership.ListMembershipsRequest.serialize, + response_deserializer=membership.ListMembershipsResponse.deserialize, + ) + return self._stubs['list_memberships'] + + @property + def get_membership(self) -> Callable[ + [membership.GetMembershipRequest], + membership.Membership]: + r"""Return a callable for the get membership method over gRPC. + + Returns details about a membership. For an example, see `Get + details about a user's or Google Chat app's + membership `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Returns: + Callable[[~.GetMembershipRequest], + ~.Membership]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_membership' not in self._stubs: + self._stubs['get_membership'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/GetMembership', + request_serializer=membership.GetMembershipRequest.serialize, + response_deserializer=membership.Membership.deserialize, + ) + return self._stubs['get_membership'] + + @property + def get_message(self) -> Callable[ + [message.GetMessageRequest], + message.Message]: + r"""Return a callable for the get message method over gRPC. + + Returns details about a message. For an example, see `Get + details about a + message `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Note: Might return a message from a blocked member or space. + + Returns: + Callable[[~.GetMessageRequest], + ~.Message]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_message' not in self._stubs: + self._stubs['get_message'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/GetMessage', + request_serializer=message.GetMessageRequest.serialize, + response_deserializer=message.Message.deserialize, + ) + return self._stubs['get_message'] + + @property + def update_message(self) -> Callable[ + [gc_message.UpdateMessageRequest], + gc_message.Message]: + r"""Return a callable for the update message method over gRPC. + + Updates a message. There's a difference between the ``patch`` + and ``update`` methods. The ``patch`` method uses a ``patch`` + request while the ``update`` method uses a ``put`` request. We + recommend using the ``patch`` method. For an example, see + `Update a + message `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + When using app authentication, requests can only update messages + created by the calling Chat app. + + Returns: + Callable[[~.UpdateMessageRequest], + ~.Message]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_message' not in self._stubs: + self._stubs['update_message'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/UpdateMessage', + request_serializer=gc_message.UpdateMessageRequest.serialize, + response_deserializer=gc_message.Message.deserialize, + ) + return self._stubs['update_message'] + + @property + def delete_message(self) -> Callable[ + [message.DeleteMessageRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete message method over gRPC. + + Deletes a message. For an example, see `Delete a + message `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + When using app authentication, requests can only delete messages + created by the calling Chat app. + + Returns: + Callable[[~.DeleteMessageRequest], + ~.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_message' not in self._stubs: + self._stubs['delete_message'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/DeleteMessage', + request_serializer=message.DeleteMessageRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_message'] + + @property + def get_attachment(self) -> Callable[ + [attachment.GetAttachmentRequest], + attachment.Attachment]: + r"""Return a callable for the get attachment method over gRPC. + + Gets the metadata of a message attachment. The attachment data + is fetched using the `media + API `__. + For an example, see `Get metadata about a message + attachment `__. + Requires `app + authentication `__. + + Returns: + Callable[[~.GetAttachmentRequest], + ~.Attachment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attachment' not in self._stubs: + self._stubs['get_attachment'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/GetAttachment', + request_serializer=attachment.GetAttachmentRequest.serialize, + response_deserializer=attachment.Attachment.deserialize, + ) + return self._stubs['get_attachment'] + + @property + def upload_attachment(self) -> Callable[ + [attachment.UploadAttachmentRequest], + attachment.UploadAttachmentResponse]: + r"""Return a callable for the upload attachment method over gRPC. + + Uploads an attachment. For an example, see `Upload media as a + file + attachment `__. + Requires user + `authentication `__. + + You can upload attachments up to 200 MB. Certain file types + aren't supported. For details, see `File types blocked by Google + Chat `__. + + Returns: + Callable[[~.UploadAttachmentRequest], + ~.UploadAttachmentResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'upload_attachment' not in self._stubs: + self._stubs['upload_attachment'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/UploadAttachment', + request_serializer=attachment.UploadAttachmentRequest.serialize, + response_deserializer=attachment.UploadAttachmentResponse.deserialize, + ) + return self._stubs['upload_attachment'] + + @property + def list_spaces(self) -> Callable[ + [space.ListSpacesRequest], + space.ListSpacesResponse]: + r"""Return a callable for the list spaces method over gRPC. + + Lists spaces the caller is a member of. Group chats and DMs + aren't listed until the first message is sent. For an example, + see `List + spaces `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Lists spaces visible to the caller or authenticated user. Group + chats and DMs aren't listed until the first message is sent. + + Returns: + Callable[[~.ListSpacesRequest], + ~.ListSpacesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_spaces' not in self._stubs: + self._stubs['list_spaces'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/ListSpaces', + request_serializer=space.ListSpacesRequest.serialize, + response_deserializer=space.ListSpacesResponse.deserialize, + ) + return self._stubs['list_spaces'] + + @property + def get_space(self) -> Callable[ + [space.GetSpaceRequest], + space.Space]: + r"""Return a callable for the get space method over gRPC. + + Returns details about a space. For an example, see `Get details + about a + space `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Returns: + Callable[[~.GetSpaceRequest], + ~.Space]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_space' not in self._stubs: + self._stubs['get_space'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/GetSpace', + request_serializer=space.GetSpaceRequest.serialize, + response_deserializer=space.Space.deserialize, + ) + return self._stubs['get_space'] + + @property + def create_space(self) -> Callable[ + [gc_space.CreateSpaceRequest], + gc_space.Space]: + r"""Return a callable for the create space method over gRPC. + + Creates a named space. Spaces grouped by topics aren't + supported. For an example, see `Create a + space `__. + + If you receive the error message ``ALREADY_EXISTS`` when + creating a space, try a different ``displayName``. An existing + space within the Google Workspace organization might already use + this display name. + + Requires `user + authentication `__. + + Returns: + Callable[[~.CreateSpaceRequest], + ~.Space]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_space' not in self._stubs: + self._stubs['create_space'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/CreateSpace', + request_serializer=gc_space.CreateSpaceRequest.serialize, + response_deserializer=gc_space.Space.deserialize, + ) + return self._stubs['create_space'] + + @property + def set_up_space(self) -> Callable[ + [space_setup.SetUpSpaceRequest], + space.Space]: + r"""Return a callable for the set up space method over gRPC. + + Creates a space and adds specified users to it. The calling user + is automatically added to the space, and shouldn't be specified + as a membership in the request. For an example, see `Set up a + space with initial + members `__. + + To specify the human members to add, add memberships with the + appropriate ``member.name`` in the ``SetUpSpaceRequest``. To add + a human user, use ``users/{user}``, where ``{user}`` can be the + email address for the user. For users in the same Workspace + organization ``{user}`` can also be the ``id`` for the person + from the People API, or the ``id`` for the user in the Directory + API. For example, if the People API Person profile ID for + ``user@example.com`` is ``123456789``, you can add the user to + the space by setting the ``membership.member.name`` to + ``users/user@example.com`` or ``users/123456789``. + + For a space or group chat, if the caller blocks or is blocked by + some members, then those members aren't added to the created + space. + + To create a direct message (DM) between the calling user and + another human user, specify exactly one membership to represent + the human user. If one user blocks the other, the request fails + and the DM isn't created. + + To create a DM between the calling user and the calling app, set + ``Space.singleUserBotDm`` to ``true`` and don't specify any + memberships. You can only use this method to set up a DM with + the calling app. To add the calling app as a member of a space + or an existing DM between two human users, see `Invite or add a + user or app to a + space `__. + + If a DM already exists between two users, even when one user + blocks the other at the time a request is made, then the + existing DM is returned. + + Spaces with threaded replies aren't supported. If you receive + the error message ``ALREADY_EXISTS`` when setting up a space, + try a different ``displayName``. An existing space within the + Google Workspace organization might already use this display + name. + + Requires `user + authentication `__. + + Returns: + Callable[[~.SetUpSpaceRequest], + ~.Space]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_up_space' not in self._stubs: + self._stubs['set_up_space'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/SetUpSpace', + request_serializer=space_setup.SetUpSpaceRequest.serialize, + response_deserializer=space.Space.deserialize, + ) + return self._stubs['set_up_space'] + + @property + def update_space(self) -> Callable[ + [gc_space.UpdateSpaceRequest], + gc_space.Space]: + r"""Return a callable for the update space method over gRPC. + + Updates a space. For an example, see `Update a + space `__. + + If you're updating the ``displayName`` field and receive the + error message ``ALREADY_EXISTS``, try a different display name.. + An existing space within the Google Workspace organization might + already use this display name. + + Requires `user + authentication `__. + + Returns: + Callable[[~.UpdateSpaceRequest], + ~.Space]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_space' not in self._stubs: + self._stubs['update_space'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/UpdateSpace', + request_serializer=gc_space.UpdateSpaceRequest.serialize, + response_deserializer=gc_space.Space.deserialize, + ) + return self._stubs['update_space'] + + @property + def delete_space(self) -> Callable[ + [space.DeleteSpaceRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete space method over gRPC. + + Deletes a named space. Always performs a cascading delete, which + means that the space's child resources—like messages posted in + the space and memberships in the space—are also deleted. For an + example, see `Delete a + space `__. + Requires `user + authentication `__ + from a user who has permission to delete the space. + + Returns: + Callable[[~.DeleteSpaceRequest], + ~.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_space' not in self._stubs: + self._stubs['delete_space'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/DeleteSpace', + request_serializer=space.DeleteSpaceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_space'] + + @property + def complete_import_space(self) -> Callable[ + [space.CompleteImportSpaceRequest], + space.CompleteImportSpaceResponse]: + r"""Return a callable for the complete import space method over gRPC. + + Completes the `import + process `__ + for the specified space and makes it visible to users. Requires + app authentication and domain-wide delegation. For more + information, see `Authorize Google Chat apps to import + data `__. + + Returns: + Callable[[~.CompleteImportSpaceRequest], + ~.CompleteImportSpaceResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_import_space' not in self._stubs: + self._stubs['complete_import_space'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/CompleteImportSpace', + request_serializer=space.CompleteImportSpaceRequest.serialize, + response_deserializer=space.CompleteImportSpaceResponse.deserialize, + ) + return self._stubs['complete_import_space'] + + @property + def find_direct_message(self) -> Callable[ + [space.FindDirectMessageRequest], + space.Space]: + r"""Return a callable for the find direct message method over gRPC. + + Returns the existing direct message with the specified user. If + no direct message space is found, returns a ``404 NOT_FOUND`` + error. For an example, see `Find a direct + message `__. + + With `user + authentication `__, + returns the direct message space between the specified user and + the authenticated user. + + With `app + authentication `__, + returns the direct message space between the specified user and + the calling Chat app. + + Requires `user + authentication `__ + or `app + authentication `__. + + Returns: + Callable[[~.FindDirectMessageRequest], + ~.Space]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'find_direct_message' not in self._stubs: + self._stubs['find_direct_message'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/FindDirectMessage', + request_serializer=space.FindDirectMessageRequest.serialize, + response_deserializer=space.Space.deserialize, + ) + return self._stubs['find_direct_message'] + + @property + def create_membership(self) -> Callable[ + [gc_membership.CreateMembershipRequest], + gc_membership.Membership]: + r"""Return a callable for the create membership method over gRPC. + + Creates a human membership or app membership for the calling + app. Creating memberships for other apps isn't supported. For an + example, see `Invite or add a user or a Google Chat app to a + space `__. + When creating a membership, if the specified member has their + auto-accept policy turned off, then they're invited, and must + accept the space invitation before joining. Otherwise, creating + a membership adds the member directly to the specified space. + Requires `user + authentication `__. + + To specify the member to add, set the ``membership.member.name`` + in the ``CreateMembershipRequest``: + + - To add the calling app to a space or a direct message between + two human users, use ``users/app``. Unable to add other apps + to the space. + + - To add a human user, use ``users/{user}``, where ``{user}`` + can be the email address for the user. For users in the same + Workspace organization ``{user}`` can also be the ``id`` for + the person from the People API, or the ``id`` for the user in + the Directory API. For example, if the People API Person + profile ID for ``user@example.com`` is ``123456789``, you can + add the user to the space by setting the + ``membership.member.name`` to ``users/user@example.com`` or + ``users/123456789``. + + Returns: + Callable[[~.CreateMembershipRequest], + ~.Membership]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_membership' not in self._stubs: + self._stubs['create_membership'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/CreateMembership', + request_serializer=gc_membership.CreateMembershipRequest.serialize, + response_deserializer=gc_membership.Membership.deserialize, + ) + return self._stubs['create_membership'] + + @property + def update_membership(self) -> Callable[ + [gc_membership.UpdateMembershipRequest], + gc_membership.Membership]: + r"""Return a callable for the update membership method over gRPC. + + Updates a membership. Requires `user + authentication `__. + + Returns: + Callable[[~.UpdateMembershipRequest], + ~.Membership]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_membership' not in self._stubs: + self._stubs['update_membership'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/UpdateMembership', + request_serializer=gc_membership.UpdateMembershipRequest.serialize, + response_deserializer=gc_membership.Membership.deserialize, + ) + return self._stubs['update_membership'] + + @property + def delete_membership(self) -> Callable[ + [membership.DeleteMembershipRequest], + membership.Membership]: + r"""Return a callable for the delete membership method over gRPC. + + Deletes a membership. For an example, see `Remove a user or a + Google Chat app from a + space `__. + + Requires `user + authentication `__. + + Returns: + Callable[[~.DeleteMembershipRequest], + ~.Membership]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_membership' not in self._stubs: + self._stubs['delete_membership'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/DeleteMembership', + request_serializer=membership.DeleteMembershipRequest.serialize, + response_deserializer=membership.Membership.deserialize, + ) + return self._stubs['delete_membership'] + + @property + def create_reaction(self) -> Callable[ + [gc_reaction.CreateReactionRequest], + gc_reaction.Reaction]: + r"""Return a callable for the create reaction method over gRPC. + + Creates a reaction and adds it to a message. Only unicode emojis + are supported. For an example, see `Add a reaction to a + message `__. + Requires `user + authentication `__. + + Returns: + Callable[[~.CreateReactionRequest], + ~.Reaction]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_reaction' not in self._stubs: + self._stubs['create_reaction'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/CreateReaction', + request_serializer=gc_reaction.CreateReactionRequest.serialize, + response_deserializer=gc_reaction.Reaction.deserialize, + ) + return self._stubs['create_reaction'] + + @property + def list_reactions(self) -> Callable[ + [reaction.ListReactionsRequest], + reaction.ListReactionsResponse]: + r"""Return a callable for the list reactions method over gRPC. + + Lists reactions to a message. For an example, see `List + reactions for a + message `__. + Requires `user + authentication `__. + + Returns: + Callable[[~.ListReactionsRequest], + ~.ListReactionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_reactions' not in self._stubs: + self._stubs['list_reactions'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/ListReactions', + request_serializer=reaction.ListReactionsRequest.serialize, + response_deserializer=reaction.ListReactionsResponse.deserialize, + ) + return self._stubs['list_reactions'] + + @property + def delete_reaction(self) -> Callable[ + [reaction.DeleteReactionRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete reaction method over gRPC. + + Deletes a reaction to a message. Only unicode emojis are + supported. For an example, see `Delete a + reaction `__. + Requires `user + authentication `__. + + Returns: + Callable[[~.DeleteReactionRequest], + ~.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_reaction' not in self._stubs: + self._stubs['delete_reaction'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/DeleteReaction', + request_serializer=reaction.DeleteReactionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_reaction'] + + @property + def get_space_read_state(self) -> Callable[ + [space_read_state.GetSpaceReadStateRequest], + space_read_state.SpaceReadState]: + r"""Return a callable for the get space read state method over gRPC. + + Returns details about a user's read state within a space, used + to identify read and unread messages. + + Requires `user + authentication `__. + + Returns: + Callable[[~.GetSpaceReadStateRequest], + ~.SpaceReadState]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_space_read_state' not in self._stubs: + self._stubs['get_space_read_state'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/GetSpaceReadState', + request_serializer=space_read_state.GetSpaceReadStateRequest.serialize, + response_deserializer=space_read_state.SpaceReadState.deserialize, + ) + return self._stubs['get_space_read_state'] + + @property + def update_space_read_state(self) -> Callable[ + [gc_space_read_state.UpdateSpaceReadStateRequest], + gc_space_read_state.SpaceReadState]: + r"""Return a callable for the update space read state method over gRPC. + + Updates a user's read state within a space, used to identify + read and unread messages. + + Requires `user + authentication `__. + + Returns: + Callable[[~.UpdateSpaceReadStateRequest], + ~.SpaceReadState]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_space_read_state' not in self._stubs: + self._stubs['update_space_read_state'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/UpdateSpaceReadState', + request_serializer=gc_space_read_state.UpdateSpaceReadStateRequest.serialize, + response_deserializer=gc_space_read_state.SpaceReadState.deserialize, + ) + return self._stubs['update_space_read_state'] + + @property + def get_thread_read_state(self) -> Callable[ + [thread_read_state.GetThreadReadStateRequest], + thread_read_state.ThreadReadState]: + r"""Return a callable for the get thread read state method over gRPC. + + Returns details about a user's read state within a thread, used + to identify read and unread messages. + + Requires `user + authentication `__. + + Returns: + Callable[[~.GetThreadReadStateRequest], + ~.ThreadReadState]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_thread_read_state' not in self._stubs: + self._stubs['get_thread_read_state'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/GetThreadReadState', + request_serializer=thread_read_state.GetThreadReadStateRequest.serialize, + response_deserializer=thread_read_state.ThreadReadState.deserialize, + ) + return self._stubs['get_thread_read_state'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ChatServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/transports/grpc_asyncio.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..e748d296b6aa --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/transports/grpc_asyncio.py @@ -0,0 +1,1189 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.apps.chat_v1.types import attachment +from google.apps.chat_v1.types import membership +from google.apps.chat_v1.types import membership as gc_membership +from google.apps.chat_v1.types import message +from google.apps.chat_v1.types import message as gc_message +from google.apps.chat_v1.types import reaction +from google.apps.chat_v1.types import reaction as gc_reaction +from google.apps.chat_v1.types import space +from google.apps.chat_v1.types import space as gc_space +from google.apps.chat_v1.types import space_read_state +from google.apps.chat_v1.types import space_read_state as gc_space_read_state +from google.apps.chat_v1.types import space_setup +from google.apps.chat_v1.types import thread_read_state +from google.protobuf import empty_pb2 # type: ignore +from .base import ChatServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ChatServiceGrpcTransport + + +class ChatServiceGrpcAsyncIOTransport(ChatServiceTransport): + """gRPC AsyncIO backend transport for ChatService. + + Enables developers to build Chat apps and + integrations on Google Chat Platform. + + 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 = 'chat.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + 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 = 'chat.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'chat.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``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, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_message(self) -> Callable[ + [gc_message.CreateMessageRequest], + Awaitable[gc_message.Message]]: + r"""Return a callable for the create message method over gRPC. + + Creates a message in a Google Chat space. For an example, see + `Send a + message `__. + + Calling this method requires + `authentication `__ + and supports the following authentication types: + + - For text messages, user authentication or app authentication + are supported. + - For card messages, only app authentication is supported. + (Only Chat apps can create card messages.) + + Returns: + Callable[[~.CreateMessageRequest], + Awaitable[~.Message]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_message' not in self._stubs: + self._stubs['create_message'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/CreateMessage', + request_serializer=gc_message.CreateMessageRequest.serialize, + response_deserializer=gc_message.Message.deserialize, + ) + return self._stubs['create_message'] + + @property + def list_messages(self) -> Callable[ + [message.ListMessagesRequest], + Awaitable[message.ListMessagesResponse]]: + r"""Return a callable for the list messages method over gRPC. + + Lists messages in a space that the caller is a member of, + including messages from blocked members and spaces. For an + example, see `List + messages `__. Requires `user + authentication `__. + + 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.chat.v1.ChatService/ListMessages', + request_serializer=message.ListMessagesRequest.serialize, + response_deserializer=message.ListMessagesResponse.deserialize, + ) + return self._stubs['list_messages'] + + @property + def list_memberships(self) -> Callable[ + [membership.ListMembershipsRequest], + Awaitable[membership.ListMembershipsResponse]]: + r"""Return a callable for the list memberships method over gRPC. + + Lists memberships in a space. For an example, see `List users + and Google Chat apps in a + space `__. + Listing memberships with `app + authentication `__ + lists memberships in spaces that the Chat app has access to, but + excludes Chat app memberships, including its own. Listing + memberships with `User + authentication `__ + lists memberships in spaces that the authenticated user has + access to. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Returns: + Callable[[~.ListMembershipsRequest], + Awaitable[~.ListMembershipsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_memberships' not in self._stubs: + self._stubs['list_memberships'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/ListMemberships', + request_serializer=membership.ListMembershipsRequest.serialize, + response_deserializer=membership.ListMembershipsResponse.deserialize, + ) + return self._stubs['list_memberships'] + + @property + def get_membership(self) -> Callable[ + [membership.GetMembershipRequest], + Awaitable[membership.Membership]]: + r"""Return a callable for the get membership method over gRPC. + + Returns details about a membership. For an example, see `Get + details about a user's or Google Chat app's + membership `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Returns: + Callable[[~.GetMembershipRequest], + Awaitable[~.Membership]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_membership' not in self._stubs: + self._stubs['get_membership'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/GetMembership', + request_serializer=membership.GetMembershipRequest.serialize, + response_deserializer=membership.Membership.deserialize, + ) + return self._stubs['get_membership'] + + @property + def get_message(self) -> Callable[ + [message.GetMessageRequest], + Awaitable[message.Message]]: + r"""Return a callable for the get message method over gRPC. + + Returns details about a message. For an example, see `Get + details about a + message `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Note: Might return a message from a blocked member or space. + + Returns: + Callable[[~.GetMessageRequest], + Awaitable[~.Message]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_message' not in self._stubs: + self._stubs['get_message'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/GetMessage', + request_serializer=message.GetMessageRequest.serialize, + response_deserializer=message.Message.deserialize, + ) + return self._stubs['get_message'] + + @property + def update_message(self) -> Callable[ + [gc_message.UpdateMessageRequest], + Awaitable[gc_message.Message]]: + r"""Return a callable for the update message method over gRPC. + + Updates a message. There's a difference between the ``patch`` + and ``update`` methods. The ``patch`` method uses a ``patch`` + request while the ``update`` method uses a ``put`` request. We + recommend using the ``patch`` method. For an example, see + `Update a + message `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + When using app authentication, requests can only update messages + created by the calling Chat app. + + Returns: + Callable[[~.UpdateMessageRequest], + Awaitable[~.Message]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_message' not in self._stubs: + self._stubs['update_message'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/UpdateMessage', + request_serializer=gc_message.UpdateMessageRequest.serialize, + response_deserializer=gc_message.Message.deserialize, + ) + return self._stubs['update_message'] + + @property + def delete_message(self) -> Callable[ + [message.DeleteMessageRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete message method over gRPC. + + Deletes a message. For an example, see `Delete a + message `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + When using app authentication, requests can only delete messages + created by the calling Chat app. + + Returns: + Callable[[~.DeleteMessageRequest], + 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_message' not in self._stubs: + self._stubs['delete_message'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/DeleteMessage', + request_serializer=message.DeleteMessageRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_message'] + + @property + def get_attachment(self) -> Callable[ + [attachment.GetAttachmentRequest], + Awaitable[attachment.Attachment]]: + r"""Return a callable for the get attachment method over gRPC. + + Gets the metadata of a message attachment. The attachment data + is fetched using the `media + API `__. + For an example, see `Get metadata about a message + attachment `__. + Requires `app + authentication `__. + + Returns: + Callable[[~.GetAttachmentRequest], + Awaitable[~.Attachment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attachment' not in self._stubs: + self._stubs['get_attachment'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/GetAttachment', + request_serializer=attachment.GetAttachmentRequest.serialize, + response_deserializer=attachment.Attachment.deserialize, + ) + return self._stubs['get_attachment'] + + @property + def upload_attachment(self) -> Callable[ + [attachment.UploadAttachmentRequest], + Awaitable[attachment.UploadAttachmentResponse]]: + r"""Return a callable for the upload attachment method over gRPC. + + Uploads an attachment. For an example, see `Upload media as a + file + attachment `__. + Requires user + `authentication `__. + + You can upload attachments up to 200 MB. Certain file types + aren't supported. For details, see `File types blocked by Google + Chat `__. + + Returns: + Callable[[~.UploadAttachmentRequest], + Awaitable[~.UploadAttachmentResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'upload_attachment' not in self._stubs: + self._stubs['upload_attachment'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/UploadAttachment', + request_serializer=attachment.UploadAttachmentRequest.serialize, + response_deserializer=attachment.UploadAttachmentResponse.deserialize, + ) + return self._stubs['upload_attachment'] + + @property + def list_spaces(self) -> Callable[ + [space.ListSpacesRequest], + Awaitable[space.ListSpacesResponse]]: + r"""Return a callable for the list spaces method over gRPC. + + Lists spaces the caller is a member of. Group chats and DMs + aren't listed until the first message is sent. For an example, + see `List + spaces `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Lists spaces visible to the caller or authenticated user. Group + chats and DMs aren't listed until the first message is sent. + + Returns: + Callable[[~.ListSpacesRequest], + Awaitable[~.ListSpacesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_spaces' not in self._stubs: + self._stubs['list_spaces'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/ListSpaces', + request_serializer=space.ListSpacesRequest.serialize, + response_deserializer=space.ListSpacesResponse.deserialize, + ) + return self._stubs['list_spaces'] + + @property + def get_space(self) -> Callable[ + [space.GetSpaceRequest], + Awaitable[space.Space]]: + r"""Return a callable for the get space method over gRPC. + + Returns details about a space. For an example, see `Get details + about a + space `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Returns: + Callable[[~.GetSpaceRequest], + Awaitable[~.Space]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_space' not in self._stubs: + self._stubs['get_space'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/GetSpace', + request_serializer=space.GetSpaceRequest.serialize, + response_deserializer=space.Space.deserialize, + ) + return self._stubs['get_space'] + + @property + def create_space(self) -> Callable[ + [gc_space.CreateSpaceRequest], + Awaitable[gc_space.Space]]: + r"""Return a callable for the create space method over gRPC. + + Creates a named space. Spaces grouped by topics aren't + supported. For an example, see `Create a + space `__. + + If you receive the error message ``ALREADY_EXISTS`` when + creating a space, try a different ``displayName``. An existing + space within the Google Workspace organization might already use + this display name. + + Requires `user + authentication `__. + + Returns: + Callable[[~.CreateSpaceRequest], + Awaitable[~.Space]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_space' not in self._stubs: + self._stubs['create_space'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/CreateSpace', + request_serializer=gc_space.CreateSpaceRequest.serialize, + response_deserializer=gc_space.Space.deserialize, + ) + return self._stubs['create_space'] + + @property + def set_up_space(self) -> Callable[ + [space_setup.SetUpSpaceRequest], + Awaitable[space.Space]]: + r"""Return a callable for the set up space method over gRPC. + + Creates a space and adds specified users to it. The calling user + is automatically added to the space, and shouldn't be specified + as a membership in the request. For an example, see `Set up a + space with initial + members `__. + + To specify the human members to add, add memberships with the + appropriate ``member.name`` in the ``SetUpSpaceRequest``. To add + a human user, use ``users/{user}``, where ``{user}`` can be the + email address for the user. For users in the same Workspace + organization ``{user}`` can also be the ``id`` for the person + from the People API, or the ``id`` for the user in the Directory + API. For example, if the People API Person profile ID for + ``user@example.com`` is ``123456789``, you can add the user to + the space by setting the ``membership.member.name`` to + ``users/user@example.com`` or ``users/123456789``. + + For a space or group chat, if the caller blocks or is blocked by + some members, then those members aren't added to the created + space. + + To create a direct message (DM) between the calling user and + another human user, specify exactly one membership to represent + the human user. If one user blocks the other, the request fails + and the DM isn't created. + + To create a DM between the calling user and the calling app, set + ``Space.singleUserBotDm`` to ``true`` and don't specify any + memberships. You can only use this method to set up a DM with + the calling app. To add the calling app as a member of a space + or an existing DM between two human users, see `Invite or add a + user or app to a + space `__. + + If a DM already exists between two users, even when one user + blocks the other at the time a request is made, then the + existing DM is returned. + + Spaces with threaded replies aren't supported. If you receive + the error message ``ALREADY_EXISTS`` when setting up a space, + try a different ``displayName``. An existing space within the + Google Workspace organization might already use this display + name. + + Requires `user + authentication `__. + + Returns: + Callable[[~.SetUpSpaceRequest], + Awaitable[~.Space]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_up_space' not in self._stubs: + self._stubs['set_up_space'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/SetUpSpace', + request_serializer=space_setup.SetUpSpaceRequest.serialize, + response_deserializer=space.Space.deserialize, + ) + return self._stubs['set_up_space'] + + @property + def update_space(self) -> Callable[ + [gc_space.UpdateSpaceRequest], + Awaitable[gc_space.Space]]: + r"""Return a callable for the update space method over gRPC. + + Updates a space. For an example, see `Update a + space `__. + + If you're updating the ``displayName`` field and receive the + error message ``ALREADY_EXISTS``, try a different display name.. + An existing space within the Google Workspace organization might + already use this display name. + + Requires `user + authentication `__. + + Returns: + Callable[[~.UpdateSpaceRequest], + Awaitable[~.Space]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_space' not in self._stubs: + self._stubs['update_space'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/UpdateSpace', + request_serializer=gc_space.UpdateSpaceRequest.serialize, + response_deserializer=gc_space.Space.deserialize, + ) + return self._stubs['update_space'] + + @property + def delete_space(self) -> Callable[ + [space.DeleteSpaceRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete space method over gRPC. + + Deletes a named space. Always performs a cascading delete, which + means that the space's child resources—like messages posted in + the space and memberships in the space—are also deleted. For an + example, see `Delete a + space `__. + Requires `user + authentication `__ + from a user who has permission to delete the space. + + Returns: + Callable[[~.DeleteSpaceRequest], + 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_space' not in self._stubs: + self._stubs['delete_space'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/DeleteSpace', + request_serializer=space.DeleteSpaceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_space'] + + @property + def complete_import_space(self) -> Callable[ + [space.CompleteImportSpaceRequest], + Awaitable[space.CompleteImportSpaceResponse]]: + r"""Return a callable for the complete import space method over gRPC. + + Completes the `import + process `__ + for the specified space and makes it visible to users. Requires + app authentication and domain-wide delegation. For more + information, see `Authorize Google Chat apps to import + data `__. + + Returns: + Callable[[~.CompleteImportSpaceRequest], + Awaitable[~.CompleteImportSpaceResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_import_space' not in self._stubs: + self._stubs['complete_import_space'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/CompleteImportSpace', + request_serializer=space.CompleteImportSpaceRequest.serialize, + response_deserializer=space.CompleteImportSpaceResponse.deserialize, + ) + return self._stubs['complete_import_space'] + + @property + def find_direct_message(self) -> Callable[ + [space.FindDirectMessageRequest], + Awaitable[space.Space]]: + r"""Return a callable for the find direct message method over gRPC. + + Returns the existing direct message with the specified user. If + no direct message space is found, returns a ``404 NOT_FOUND`` + error. For an example, see `Find a direct + message `__. + + With `user + authentication `__, + returns the direct message space between the specified user and + the authenticated user. + + With `app + authentication `__, + returns the direct message space between the specified user and + the calling Chat app. + + Requires `user + authentication `__ + or `app + authentication `__. + + Returns: + Callable[[~.FindDirectMessageRequest], + Awaitable[~.Space]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'find_direct_message' not in self._stubs: + self._stubs['find_direct_message'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/FindDirectMessage', + request_serializer=space.FindDirectMessageRequest.serialize, + response_deserializer=space.Space.deserialize, + ) + return self._stubs['find_direct_message'] + + @property + def create_membership(self) -> Callable[ + [gc_membership.CreateMembershipRequest], + Awaitable[gc_membership.Membership]]: + r"""Return a callable for the create membership method over gRPC. + + Creates a human membership or app membership for the calling + app. Creating memberships for other apps isn't supported. For an + example, see `Invite or add a user or a Google Chat app to a + space `__. + When creating a membership, if the specified member has their + auto-accept policy turned off, then they're invited, and must + accept the space invitation before joining. Otherwise, creating + a membership adds the member directly to the specified space. + Requires `user + authentication `__. + + To specify the member to add, set the ``membership.member.name`` + in the ``CreateMembershipRequest``: + + - To add the calling app to a space or a direct message between + two human users, use ``users/app``. Unable to add other apps + to the space. + + - To add a human user, use ``users/{user}``, where ``{user}`` + can be the email address for the user. For users in the same + Workspace organization ``{user}`` can also be the ``id`` for + the person from the People API, or the ``id`` for the user in + the Directory API. For example, if the People API Person + profile ID for ``user@example.com`` is ``123456789``, you can + add the user to the space by setting the + ``membership.member.name`` to ``users/user@example.com`` or + ``users/123456789``. + + Returns: + Callable[[~.CreateMembershipRequest], + Awaitable[~.Membership]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_membership' not in self._stubs: + self._stubs['create_membership'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/CreateMembership', + request_serializer=gc_membership.CreateMembershipRequest.serialize, + response_deserializer=gc_membership.Membership.deserialize, + ) + return self._stubs['create_membership'] + + @property + def update_membership(self) -> Callable[ + [gc_membership.UpdateMembershipRequest], + Awaitable[gc_membership.Membership]]: + r"""Return a callable for the update membership method over gRPC. + + Updates a membership. Requires `user + authentication `__. + + Returns: + Callable[[~.UpdateMembershipRequest], + Awaitable[~.Membership]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_membership' not in self._stubs: + self._stubs['update_membership'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/UpdateMembership', + request_serializer=gc_membership.UpdateMembershipRequest.serialize, + response_deserializer=gc_membership.Membership.deserialize, + ) + return self._stubs['update_membership'] + + @property + def delete_membership(self) -> Callable[ + [membership.DeleteMembershipRequest], + Awaitable[membership.Membership]]: + r"""Return a callable for the delete membership method over gRPC. + + Deletes a membership. For an example, see `Remove a user or a + Google Chat app from a + space `__. + + Requires `user + authentication `__. + + Returns: + Callable[[~.DeleteMembershipRequest], + Awaitable[~.Membership]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_membership' not in self._stubs: + self._stubs['delete_membership'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/DeleteMembership', + request_serializer=membership.DeleteMembershipRequest.serialize, + response_deserializer=membership.Membership.deserialize, + ) + return self._stubs['delete_membership'] + + @property + def create_reaction(self) -> Callable[ + [gc_reaction.CreateReactionRequest], + Awaitable[gc_reaction.Reaction]]: + r"""Return a callable for the create reaction method over gRPC. + + Creates a reaction and adds it to a message. Only unicode emojis + are supported. For an example, see `Add a reaction to a + message `__. + Requires `user + authentication `__. + + Returns: + Callable[[~.CreateReactionRequest], + Awaitable[~.Reaction]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_reaction' not in self._stubs: + self._stubs['create_reaction'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/CreateReaction', + request_serializer=gc_reaction.CreateReactionRequest.serialize, + response_deserializer=gc_reaction.Reaction.deserialize, + ) + return self._stubs['create_reaction'] + + @property + def list_reactions(self) -> Callable[ + [reaction.ListReactionsRequest], + Awaitable[reaction.ListReactionsResponse]]: + r"""Return a callable for the list reactions method over gRPC. + + Lists reactions to a message. For an example, see `List + reactions for a + message `__. + Requires `user + authentication `__. + + Returns: + Callable[[~.ListReactionsRequest], + Awaitable[~.ListReactionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_reactions' not in self._stubs: + self._stubs['list_reactions'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/ListReactions', + request_serializer=reaction.ListReactionsRequest.serialize, + response_deserializer=reaction.ListReactionsResponse.deserialize, + ) + return self._stubs['list_reactions'] + + @property + def delete_reaction(self) -> Callable[ + [reaction.DeleteReactionRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete reaction method over gRPC. + + Deletes a reaction to a message. Only unicode emojis are + supported. For an example, see `Delete a + reaction `__. + Requires `user + authentication `__. + + Returns: + Callable[[~.DeleteReactionRequest], + 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_reaction' not in self._stubs: + self._stubs['delete_reaction'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/DeleteReaction', + request_serializer=reaction.DeleteReactionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_reaction'] + + @property + def get_space_read_state(self) -> Callable[ + [space_read_state.GetSpaceReadStateRequest], + Awaitable[space_read_state.SpaceReadState]]: + r"""Return a callable for the get space read state method over gRPC. + + Returns details about a user's read state within a space, used + to identify read and unread messages. + + Requires `user + authentication `__. + + Returns: + Callable[[~.GetSpaceReadStateRequest], + Awaitable[~.SpaceReadState]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_space_read_state' not in self._stubs: + self._stubs['get_space_read_state'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/GetSpaceReadState', + request_serializer=space_read_state.GetSpaceReadStateRequest.serialize, + response_deserializer=space_read_state.SpaceReadState.deserialize, + ) + return self._stubs['get_space_read_state'] + + @property + def update_space_read_state(self) -> Callable[ + [gc_space_read_state.UpdateSpaceReadStateRequest], + Awaitable[gc_space_read_state.SpaceReadState]]: + r"""Return a callable for the update space read state method over gRPC. + + Updates a user's read state within a space, used to identify + read and unread messages. + + Requires `user + authentication `__. + + Returns: + Callable[[~.UpdateSpaceReadStateRequest], + Awaitable[~.SpaceReadState]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_space_read_state' not in self._stubs: + self._stubs['update_space_read_state'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/UpdateSpaceReadState', + request_serializer=gc_space_read_state.UpdateSpaceReadStateRequest.serialize, + response_deserializer=gc_space_read_state.SpaceReadState.deserialize, + ) + return self._stubs['update_space_read_state'] + + @property + def get_thread_read_state(self) -> Callable[ + [thread_read_state.GetThreadReadStateRequest], + Awaitable[thread_read_state.ThreadReadState]]: + r"""Return a callable for the get thread read state method over gRPC. + + Returns details about a user's read state within a thread, used + to identify read and unread messages. + + Requires `user + authentication `__. + + Returns: + Callable[[~.GetThreadReadStateRequest], + Awaitable[~.ThreadReadState]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_thread_read_state' not in self._stubs: + self._stubs['get_thread_read_state'] = self.grpc_channel.unary_unary( + '/google.chat.v1.ChatService/GetThreadReadState', + request_serializer=thread_read_state.GetThreadReadStateRequest.serialize, + response_deserializer=thread_read_state.ThreadReadState.deserialize, + ) + return self._stubs['get_thread_read_state'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ChatServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/transports/rest.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/transports/rest.py new file mode 100644 index 000000000000..cad23a339f55 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/services/chat_service/transports/rest.py @@ -0,0 +1,3105 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.apps.chat_v1.types import attachment +from google.apps.chat_v1.types import membership +from google.apps.chat_v1.types import membership as gc_membership +from google.apps.chat_v1.types import message +from google.apps.chat_v1.types import message as gc_message +from google.apps.chat_v1.types import reaction +from google.apps.chat_v1.types import reaction as gc_reaction +from google.apps.chat_v1.types import space +from google.apps.chat_v1.types import space as gc_space +from google.apps.chat_v1.types import space_read_state +from google.apps.chat_v1.types import space_read_state as gc_space_read_state +from google.apps.chat_v1.types import space_setup +from google.apps.chat_v1.types import thread_read_state +from google.protobuf import empty_pb2 # type: ignore + +from .base import ChatServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class ChatServiceRestInterceptor: + """Interceptor for ChatService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the ChatServiceRestTransport. + + .. code-block:: python + class MyCustomChatServiceInterceptor(ChatServiceRestInterceptor): + def pre_complete_import_space(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_complete_import_space(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_membership(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_membership(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_message(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_message(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_reaction(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_reaction(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_space(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_space(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_membership(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_membership(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_message(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_reaction(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_space(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_find_direct_message(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_find_direct_message(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_attachment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_attachment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_membership(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_membership(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_message(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_message(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_space(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_space(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_space_read_state(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_space_read_state(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_thread_read_state(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_thread_read_state(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_memberships(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_memberships(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_messages(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_messages(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_reactions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_reactions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_spaces(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_spaces(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_up_space(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_up_space(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_membership(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_membership(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_message(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_message(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_space(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_space(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_space_read_state(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_space_read_state(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_upload_attachment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_upload_attachment(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ChatServiceRestTransport(interceptor=MyCustomChatServiceInterceptor()) + client = ChatServiceClient(transport=transport) + + + """ + def pre_complete_import_space(self, request: space.CompleteImportSpaceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[space.CompleteImportSpaceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for complete_import_space + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_complete_import_space(self, response: space.CompleteImportSpaceResponse) -> space.CompleteImportSpaceResponse: + """Post-rpc interceptor for complete_import_space + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + def pre_create_membership(self, request: gc_membership.CreateMembershipRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gc_membership.CreateMembershipRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_membership + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_create_membership(self, response: gc_membership.Membership) -> gc_membership.Membership: + """Post-rpc interceptor for create_membership + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + def pre_create_message(self, request: gc_message.CreateMessageRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gc_message.CreateMessageRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_message + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_create_message(self, response: gc_message.Message) -> gc_message.Message: + """Post-rpc interceptor for create_message + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + def pre_create_reaction(self, request: gc_reaction.CreateReactionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gc_reaction.CreateReactionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_reaction + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_create_reaction(self, response: gc_reaction.Reaction) -> gc_reaction.Reaction: + """Post-rpc interceptor for create_reaction + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + def pre_create_space(self, request: gc_space.CreateSpaceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gc_space.CreateSpaceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_space + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_create_space(self, response: gc_space.Space) -> gc_space.Space: + """Post-rpc interceptor for create_space + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + def pre_delete_membership(self, request: membership.DeleteMembershipRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[membership.DeleteMembershipRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_membership + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_delete_membership(self, response: membership.Membership) -> membership.Membership: + """Post-rpc interceptor for delete_membership + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + def pre_delete_message(self, request: message.DeleteMessageRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[message.DeleteMessageRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_message + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def pre_delete_reaction(self, request: reaction.DeleteReactionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[reaction.DeleteReactionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_reaction + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def pre_delete_space(self, request: space.DeleteSpaceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[space.DeleteSpaceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_space + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def pre_find_direct_message(self, request: space.FindDirectMessageRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[space.FindDirectMessageRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for find_direct_message + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_find_direct_message(self, response: space.Space) -> space.Space: + """Post-rpc interceptor for find_direct_message + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + def pre_get_attachment(self, request: attachment.GetAttachmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[attachment.GetAttachmentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_attachment + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_get_attachment(self, response: attachment.Attachment) -> attachment.Attachment: + """Post-rpc interceptor for get_attachment + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + def pre_get_membership(self, request: membership.GetMembershipRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[membership.GetMembershipRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_membership + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_get_membership(self, response: membership.Membership) -> membership.Membership: + """Post-rpc interceptor for get_membership + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + def pre_get_message(self, request: message.GetMessageRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[message.GetMessageRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_message + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_get_message(self, response: message.Message) -> message.Message: + """Post-rpc interceptor for get_message + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + def pre_get_space(self, request: space.GetSpaceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[space.GetSpaceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_space + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_get_space(self, response: space.Space) -> space.Space: + """Post-rpc interceptor for get_space + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + def pre_get_space_read_state(self, request: space_read_state.GetSpaceReadStateRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[space_read_state.GetSpaceReadStateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_space_read_state + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_get_space_read_state(self, response: space_read_state.SpaceReadState) -> space_read_state.SpaceReadState: + """Post-rpc interceptor for get_space_read_state + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + def pre_get_thread_read_state(self, request: thread_read_state.GetThreadReadStateRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[thread_read_state.GetThreadReadStateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_thread_read_state + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_get_thread_read_state(self, response: thread_read_state.ThreadReadState) -> thread_read_state.ThreadReadState: + """Post-rpc interceptor for get_thread_read_state + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + def pre_list_memberships(self, request: membership.ListMembershipsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[membership.ListMembershipsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_memberships + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_list_memberships(self, response: membership.ListMembershipsResponse) -> membership.ListMembershipsResponse: + """Post-rpc interceptor for list_memberships + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + def pre_list_messages(self, request: message.ListMessagesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[message.ListMessagesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_messages + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_list_messages(self, response: message.ListMessagesResponse) -> message.ListMessagesResponse: + """Post-rpc interceptor for list_messages + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + def pre_list_reactions(self, request: reaction.ListReactionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[reaction.ListReactionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_reactions + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_list_reactions(self, response: reaction.ListReactionsResponse) -> reaction.ListReactionsResponse: + """Post-rpc interceptor for list_reactions + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + def pre_list_spaces(self, request: space.ListSpacesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[space.ListSpacesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_spaces + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_list_spaces(self, response: space.ListSpacesResponse) -> space.ListSpacesResponse: + """Post-rpc interceptor for list_spaces + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + def pre_set_up_space(self, request: space_setup.SetUpSpaceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[space_setup.SetUpSpaceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_up_space + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_set_up_space(self, response: space.Space) -> space.Space: + """Post-rpc interceptor for set_up_space + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + def pre_update_membership(self, request: gc_membership.UpdateMembershipRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gc_membership.UpdateMembershipRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_membership + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_update_membership(self, response: gc_membership.Membership) -> gc_membership.Membership: + """Post-rpc interceptor for update_membership + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + def pre_update_message(self, request: gc_message.UpdateMessageRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gc_message.UpdateMessageRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_message + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_update_message(self, response: gc_message.Message) -> gc_message.Message: + """Post-rpc interceptor for update_message + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + def pre_update_space(self, request: gc_space.UpdateSpaceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gc_space.UpdateSpaceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_space + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_update_space(self, response: gc_space.Space) -> gc_space.Space: + """Post-rpc interceptor for update_space + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + def pre_update_space_read_state(self, request: gc_space_read_state.UpdateSpaceReadStateRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gc_space_read_state.UpdateSpaceReadStateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_space_read_state + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_update_space_read_state(self, response: gc_space_read_state.SpaceReadState) -> gc_space_read_state.SpaceReadState: + """Post-rpc interceptor for update_space_read_state + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + def pre_upload_attachment(self, request: attachment.UploadAttachmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[attachment.UploadAttachmentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for upload_attachment + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_upload_attachment(self, response: attachment.UploadAttachmentResponse) -> attachment.UploadAttachmentResponse: + """Post-rpc interceptor for upload_attachment + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ChatServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ChatServiceRestInterceptor + + +class ChatServiceRestTransport(ChatServiceTransport): + """REST backend transport for ChatService. + + Enables developers to build Chat apps and + integrations on Google Chat Platform. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'chat.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[ChatServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'chat.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or ChatServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CompleteImportSpace(ChatServiceRestStub): + def __hash__(self): + return hash("CompleteImportSpace") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: space.CompleteImportSpaceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> space.CompleteImportSpaceResponse: + r"""Call the complete import space method over HTTP. + + Args: + request (~.space.CompleteImportSpaceRequest): + The request object. Request message for completing the + import process for a space. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.space.CompleteImportSpaceResponse: + Response message for completing the + import process for a space. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=spaces/*}:completeImport', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_complete_import_space(request, metadata) + pb_request = space.CompleteImportSpaceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = space.CompleteImportSpaceResponse() + pb_resp = space.CompleteImportSpaceResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_complete_import_space(resp) + return resp + + class _CreateMembership(ChatServiceRestStub): + def __hash__(self): + return hash("CreateMembership") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: gc_membership.CreateMembershipRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gc_membership.Membership: + r"""Call the create membership method over HTTP. + + Args: + request (~.gc_membership.CreateMembershipRequest): + The request object. Request message for creating a + membership. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gc_membership.Membership: + Represents a membership relation in + Google Chat, such as whether a user or + Chat app is invited to, part of, or + absent from a space. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=spaces/*}/members', + 'body': 'membership', + }, + ] + request, metadata = self._interceptor.pre_create_membership(request, metadata) + pb_request = gc_membership.CreateMembershipRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gc_membership.Membership() + pb_resp = gc_membership.Membership.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_membership(resp) + return resp + + class _CreateMessage(ChatServiceRestStub): + def __hash__(self): + return hash("CreateMessage") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: gc_message.CreateMessageRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gc_message.Message: + r"""Call the create message method over HTTP. + + Args: + request (~.gc_message.CreateMessageRequest): + The request object. Creates a message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gc_message.Message: + A message in a Google Chat space. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=spaces/*}/messages', + 'body': 'message', + }, + ] + request, metadata = self._interceptor.pre_create_message(request, metadata) + pb_request = gc_message.CreateMessageRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gc_message.Message() + pb_resp = gc_message.Message.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_message(resp) + return resp + + class _CreateReaction(ChatServiceRestStub): + def __hash__(self): + return hash("CreateReaction") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: gc_reaction.CreateReactionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gc_reaction.Reaction: + r"""Call the create reaction method over HTTP. + + Args: + request (~.gc_reaction.CreateReactionRequest): + The request object. Creates a reaction to a message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gc_reaction.Reaction: + A reaction to a message. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=spaces/*/messages/*}/reactions', + 'body': 'reaction', + }, + ] + request, metadata = self._interceptor.pre_create_reaction(request, metadata) + pb_request = gc_reaction.CreateReactionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gc_reaction.Reaction() + pb_resp = gc_reaction.Reaction.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_reaction(resp) + return resp + + class _CreateSpace(ChatServiceRestStub): + def __hash__(self): + return hash("CreateSpace") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: gc_space.CreateSpaceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gc_space.Space: + r"""Call the create space method over HTTP. + + Args: + request (~.gc_space.CreateSpaceRequest): + The request object. A request to create a named space. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gc_space.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/spaces', + 'body': 'space', + }, + ] + request, metadata = self._interceptor.pre_create_space(request, metadata) + pb_request = gc_space.CreateSpaceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gc_space.Space() + pb_resp = gc_space.Space.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_space(resp) + return resp + + class _DeleteMembership(ChatServiceRestStub): + def __hash__(self): + return hash("DeleteMembership") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: membership.DeleteMembershipRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> membership.Membership: + r"""Call the delete membership method over HTTP. + + Args: + request (~.membership.DeleteMembershipRequest): + The request object. Request to delete a membership in a + space. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.membership.Membership: + Represents a membership relation in + Google Chat, such as whether a user or + Chat app is invited to, part of, or + absent from a space. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=spaces/*/members/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_membership(request, metadata) + pb_request = membership.DeleteMembershipRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = membership.Membership() + pb_resp = membership.Membership.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_membership(resp) + return resp + + class _DeleteMessage(ChatServiceRestStub): + def __hash__(self): + return hash("DeleteMessage") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: message.DeleteMessageRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete message method over HTTP. + + Args: + request (~.message.DeleteMessageRequest): + The request object. Request to delete a message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=spaces/*/messages/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_message(request, metadata) + pb_request = message.DeleteMessageRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteReaction(ChatServiceRestStub): + def __hash__(self): + return hash("DeleteReaction") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: reaction.DeleteReactionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete reaction method over HTTP. + + Args: + request (~.reaction.DeleteReactionRequest): + The request object. Deletes a reaction to a message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=spaces/*/messages/*/reactions/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_reaction(request, metadata) + pb_request = reaction.DeleteReactionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteSpace(ChatServiceRestStub): + def __hash__(self): + return hash("DeleteSpace") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: space.DeleteSpaceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete space method over HTTP. + + Args: + request (~.space.DeleteSpaceRequest): + The request object. Request for deleting a space. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=spaces/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_space(request, metadata) + pb_request = space.DeleteSpaceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _FindDirectMessage(ChatServiceRestStub): + def __hash__(self): + return hash("FindDirectMessage") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "name" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: space.FindDirectMessageRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> space.Space: + r"""Call the find direct message method over HTTP. + + Args: + request (~.space.FindDirectMessageRequest): + The request object. A request to get direct message space + based on the user resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.space.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/spaces:findDirectMessage', + }, + ] + request, metadata = self._interceptor.pre_find_direct_message(request, metadata) + pb_request = space.FindDirectMessageRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = space.Space() + pb_resp = space.Space.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_find_direct_message(resp) + return resp + + class _GetAttachment(ChatServiceRestStub): + def __hash__(self): + return hash("GetAttachment") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: attachment.GetAttachmentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> attachment.Attachment: + r"""Call the get attachment method over HTTP. + + Args: + request (~.attachment.GetAttachmentRequest): + The request object. Request to get an attachment. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.attachment.Attachment: + An attachment in Google Chat. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=spaces/*/messages/*/attachments/*}', + }, + ] + request, metadata = self._interceptor.pre_get_attachment(request, metadata) + pb_request = attachment.GetAttachmentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = attachment.Attachment() + pb_resp = attachment.Attachment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_attachment(resp) + return resp + + class _GetMembership(ChatServiceRestStub): + def __hash__(self): + return hash("GetMembership") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: membership.GetMembershipRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> membership.Membership: + r"""Call the get membership method over HTTP. + + Args: + request (~.membership.GetMembershipRequest): + The request object. Request to get a membership of a + space. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.membership.Membership: + Represents a membership relation in + Google Chat, such as whether a user or + Chat app is invited to, part of, or + absent from a space. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=spaces/*/members/*}', + }, + ] + request, metadata = self._interceptor.pre_get_membership(request, metadata) + pb_request = membership.GetMembershipRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = membership.Membership() + pb_resp = membership.Membership.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_membership(resp) + return resp + + class _GetMessage(ChatServiceRestStub): + def __hash__(self): + return hash("GetMessage") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: message.GetMessageRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> message.Message: + r"""Call the get message method over HTTP. + + Args: + request (~.message.GetMessageRequest): + The request object. Request to get a message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.message.Message: + A message in a Google Chat space. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=spaces/*/messages/*}', + }, + ] + request, metadata = self._interceptor.pre_get_message(request, metadata) + pb_request = message.GetMessageRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = message.Message() + pb_resp = message.Message.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_message(resp) + return resp + + class _GetSpace(ChatServiceRestStub): + def __hash__(self): + return hash("GetSpace") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: space.GetSpaceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> space.Space: + r"""Call the get space method over HTTP. + + Args: + request (~.space.GetSpaceRequest): + The request object. A request to return a single space. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.space.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=spaces/*}', + }, + ] + request, metadata = self._interceptor.pre_get_space(request, metadata) + pb_request = space.GetSpaceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = space.Space() + pb_resp = space.Space.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_space(resp) + return resp + + class _GetSpaceReadState(ChatServiceRestStub): + def __hash__(self): + return hash("GetSpaceReadState") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: space_read_state.GetSpaceReadStateRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> space_read_state.SpaceReadState: + r"""Call the get space read state method over HTTP. + + Args: + request (~.space_read_state.GetSpaceReadStateRequest): + The request object. Request message for GetSpaceReadState + API. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.space_read_state.SpaceReadState: + A user's read state within a space, + used to identify read and unread + messages. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=users/*/spaces/*/spaceReadState}', + }, + ] + request, metadata = self._interceptor.pre_get_space_read_state(request, metadata) + pb_request = space_read_state.GetSpaceReadStateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = space_read_state.SpaceReadState() + pb_resp = space_read_state.SpaceReadState.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_space_read_state(resp) + return resp + + class _GetThreadReadState(ChatServiceRestStub): + def __hash__(self): + return hash("GetThreadReadState") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: thread_read_state.GetThreadReadStateRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> thread_read_state.ThreadReadState: + r"""Call the get thread read state method over HTTP. + + Args: + request (~.thread_read_state.GetThreadReadStateRequest): + The request object. Request message for + GetThreadReadStateRequest API. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.thread_read_state.ThreadReadState: + A user's read state within a thread, + used to identify read and unread + messages. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=users/*/spaces/*/threads/*/threadReadState}', + }, + ] + request, metadata = self._interceptor.pre_get_thread_read_state(request, metadata) + pb_request = thread_read_state.GetThreadReadStateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = thread_read_state.ThreadReadState() + pb_resp = thread_read_state.ThreadReadState.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_thread_read_state(resp) + return resp + + class _ListMemberships(ChatServiceRestStub): + def __hash__(self): + return hash("ListMemberships") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: membership.ListMembershipsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> membership.ListMembershipsResponse: + r"""Call the list memberships method over HTTP. + + Args: + request (~.membership.ListMembershipsRequest): + The request object. Request message for listing + memberships. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.membership.ListMembershipsResponse: + Response to list memberships of the + space. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=spaces/*}/members', + }, + ] + request, metadata = self._interceptor.pre_list_memberships(request, metadata) + pb_request = membership.ListMembershipsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = membership.ListMembershipsResponse() + pb_resp = membership.ListMembershipsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_memberships(resp) + return resp + + class _ListMessages(ChatServiceRestStub): + def __hash__(self): + return hash("ListMessages") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: message.ListMessagesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> message.ListMessagesResponse: + r"""Call the list messages method over HTTP. + + Args: + request (~.message.ListMessagesRequest): + The request object. Lists messages in the specified + space, that the user is a member of. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.message.ListMessagesResponse: + Response message for listing + messages. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=spaces/*}/messages', + }, + ] + request, metadata = self._interceptor.pre_list_messages(request, metadata) + pb_request = message.ListMessagesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = message.ListMessagesResponse() + pb_resp = message.ListMessagesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_messages(resp) + return resp + + class _ListReactions(ChatServiceRestStub): + def __hash__(self): + return hash("ListReactions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: reaction.ListReactionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> reaction.ListReactionsResponse: + r"""Call the list reactions method over HTTP. + + Args: + request (~.reaction.ListReactionsRequest): + The request object. Lists reactions to a message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.reaction.ListReactionsResponse: + Response to a list reactions request. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=spaces/*/messages/*}/reactions', + }, + ] + request, metadata = self._interceptor.pre_list_reactions(request, metadata) + pb_request = reaction.ListReactionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = reaction.ListReactionsResponse() + pb_resp = reaction.ListReactionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_reactions(resp) + return resp + + class _ListSpaces(ChatServiceRestStub): + def __hash__(self): + return hash("ListSpaces") + + def __call__(self, + request: space.ListSpacesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> space.ListSpacesResponse: + r"""Call the list spaces method over HTTP. + + Args: + request (~.space.ListSpacesRequest): + The request object. A request to list the spaces the + caller is a member of. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.space.ListSpacesResponse: + The response for a list spaces + request. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/spaces', + }, + ] + request, metadata = self._interceptor.pre_list_spaces(request, metadata) + pb_request = space.ListSpacesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = space.ListSpacesResponse() + pb_resp = space.ListSpacesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_spaces(resp) + return resp + + class _SetUpSpace(ChatServiceRestStub): + def __hash__(self): + return hash("SetUpSpace") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: space_setup.SetUpSpaceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> space.Space: + r"""Call the set up space method over HTTP. + + Args: + request (~.space_setup.SetUpSpaceRequest): + The request object. Request to create a space and add + specified users to it. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.space.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/spaces:setup', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_up_space(request, metadata) + pb_request = space_setup.SetUpSpaceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = space.Space() + pb_resp = space.Space.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_up_space(resp) + return resp + + class _UpdateMembership(ChatServiceRestStub): + def __hash__(self): + return hash("UpdateMembership") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: gc_membership.UpdateMembershipRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gc_membership.Membership: + r"""Call the update membership method over HTTP. + + Args: + request (~.gc_membership.UpdateMembershipRequest): + The request object. Request message for updating a + membership. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gc_membership.Membership: + Represents a membership relation in + Google Chat, such as whether a user or + Chat app is invited to, part of, or + absent from a space. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{membership.name=spaces/*/members/*}', + 'body': 'membership', + }, + ] + request, metadata = self._interceptor.pre_update_membership(request, metadata) + pb_request = gc_membership.UpdateMembershipRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gc_membership.Membership() + pb_resp = gc_membership.Membership.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_membership(resp) + return resp + + class _UpdateMessage(ChatServiceRestStub): + def __hash__(self): + return hash("UpdateMessage") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: gc_message.UpdateMessageRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gc_message.Message: + r"""Call the update message method over HTTP. + + Args: + request (~.gc_message.UpdateMessageRequest): + The request object. Request to update a message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gc_message.Message: + A message in a Google Chat space. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'put', + 'uri': '/v1/{message.name=spaces/*/messages/*}', + 'body': 'message', + }, +{ + 'method': 'patch', + 'uri': '/v1/{message.name=spaces/*/messages/*}', + 'body': 'message', + }, + ] + request, metadata = self._interceptor.pre_update_message(request, metadata) + pb_request = gc_message.UpdateMessageRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gc_message.Message() + pb_resp = gc_message.Message.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_message(resp) + return resp + + class _UpdateSpace(ChatServiceRestStub): + def __hash__(self): + return hash("UpdateSpace") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: gc_space.UpdateSpaceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gc_space.Space: + r"""Call the update space method over HTTP. + + Args: + request (~.gc_space.UpdateSpaceRequest): + The request object. A request to update a single space. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gc_space.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{space.name=spaces/*}', + 'body': 'space', + }, + ] + request, metadata = self._interceptor.pre_update_space(request, metadata) + pb_request = gc_space.UpdateSpaceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gc_space.Space() + pb_resp = gc_space.Space.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_space(resp) + return resp + + class _UpdateSpaceReadState(ChatServiceRestStub): + def __hash__(self): + return hash("UpdateSpaceReadState") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: gc_space_read_state.UpdateSpaceReadStateRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gc_space_read_state.SpaceReadState: + r"""Call the update space read state method over HTTP. + + Args: + request (~.gc_space_read_state.UpdateSpaceReadStateRequest): + The request object. Request message for + UpdateSpaceReadState API. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gc_space_read_state.SpaceReadState: + A user's read state within a space, + used to identify read and unread + messages. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{space_read_state.name=users/*/spaces/*/spaceReadState}', + 'body': 'space_read_state', + }, + ] + request, metadata = self._interceptor.pre_update_space_read_state(request, metadata) + pb_request = gc_space_read_state.UpdateSpaceReadStateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gc_space_read_state.SpaceReadState() + pb_resp = gc_space_read_state.SpaceReadState.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_space_read_state(resp) + return resp + + class _UploadAttachment(ChatServiceRestStub): + def __hash__(self): + return hash("UploadAttachment") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: attachment.UploadAttachmentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> attachment.UploadAttachmentResponse: + r"""Call the upload attachment method over HTTP. + + Args: + request (~.attachment.UploadAttachmentRequest): + The request object. Request to upload an attachment. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.attachment.UploadAttachmentResponse: + Response of uploading an attachment. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=spaces/*}/attachments:upload', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_upload_attachment(request, metadata) + pb_request = attachment.UploadAttachmentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = attachment.UploadAttachmentResponse() + pb_resp = attachment.UploadAttachmentResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_upload_attachment(resp) + return resp + + @property + def complete_import_space(self) -> Callable[ + [space.CompleteImportSpaceRequest], + space.CompleteImportSpaceResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CompleteImportSpace(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_membership(self) -> Callable[ + [gc_membership.CreateMembershipRequest], + gc_membership.Membership]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateMembership(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_message(self) -> Callable[ + [gc_message.CreateMessageRequest], + gc_message.Message]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateMessage(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_reaction(self) -> Callable[ + [gc_reaction.CreateReactionRequest], + gc_reaction.Reaction]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateReaction(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_space(self) -> Callable[ + [gc_space.CreateSpaceRequest], + gc_space.Space]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSpace(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_membership(self) -> Callable[ + [membership.DeleteMembershipRequest], + membership.Membership]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteMembership(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_message(self) -> Callable[ + [message.DeleteMessageRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteMessage(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_reaction(self) -> Callable[ + [reaction.DeleteReactionRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteReaction(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_space(self) -> Callable[ + [space.DeleteSpaceRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteSpace(self._session, self._host, self._interceptor) # type: ignore + + @property + def find_direct_message(self) -> Callable[ + [space.FindDirectMessageRequest], + space.Space]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._FindDirectMessage(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_attachment(self) -> Callable[ + [attachment.GetAttachmentRequest], + attachment.Attachment]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetAttachment(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_membership(self) -> Callable[ + [membership.GetMembershipRequest], + membership.Membership]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetMembership(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_message(self) -> Callable[ + [message.GetMessageRequest], + message.Message]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetMessage(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_space(self) -> Callable[ + [space.GetSpaceRequest], + space.Space]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSpace(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_space_read_state(self) -> Callable[ + [space_read_state.GetSpaceReadStateRequest], + space_read_state.SpaceReadState]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSpaceReadState(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_thread_read_state(self) -> Callable[ + [thread_read_state.GetThreadReadStateRequest], + thread_read_state.ThreadReadState]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetThreadReadState(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_memberships(self) -> Callable[ + [membership.ListMembershipsRequest], + membership.ListMembershipsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListMemberships(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_messages(self) -> Callable[ + [message.ListMessagesRequest], + message.ListMessagesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListMessages(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_reactions(self) -> Callable[ + [reaction.ListReactionsRequest], + reaction.ListReactionsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListReactions(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_spaces(self) -> Callable[ + [space.ListSpacesRequest], + space.ListSpacesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSpaces(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_up_space(self) -> Callable[ + [space_setup.SetUpSpaceRequest], + space.Space]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetUpSpace(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_membership(self) -> Callable[ + [gc_membership.UpdateMembershipRequest], + gc_membership.Membership]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateMembership(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_message(self) -> Callable[ + [gc_message.UpdateMessageRequest], + gc_message.Message]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateMessage(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_space(self) -> Callable[ + [gc_space.UpdateSpaceRequest], + gc_space.Space]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSpace(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_space_read_state(self) -> Callable[ + [gc_space_read_state.UpdateSpaceReadStateRequest], + gc_space_read_state.SpaceReadState]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSpaceReadState(self._session, self._host, self._interceptor) # type: ignore + + @property + def upload_attachment(self) -> Callable[ + [attachment.UploadAttachmentRequest], + attachment.UploadAttachmentResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UploadAttachment(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'ChatServiceRestTransport', +) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/__init__.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/__init__.py new file mode 100644 index 000000000000..acf757b23570 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/__init__.py @@ -0,0 +1,188 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .action_status import ( + ActionStatus, +) +from .annotation import ( + Annotation, + DriveLinkData, + RichLinkMetadata, + SlashCommandMetadata, + UserMentionMetadata, + AnnotationType, +) +from .attachment import ( + Attachment, + AttachmentDataRef, + DriveDataRef, + GetAttachmentRequest, + UploadAttachmentRequest, + UploadAttachmentResponse, +) +from .contextual_addon import ( + ContextualAddOnMarkup, +) +from .deletion_metadata import ( + DeletionMetadata, +) +from .group import ( + Group, +) +from .history_state import ( + HistoryState, +) +from .matched_url import ( + MatchedUrl, +) +from .membership import ( + CreateMembershipRequest, + DeleteMembershipRequest, + GetMembershipRequest, + ListMembershipsRequest, + ListMembershipsResponse, + Membership, + UpdateMembershipRequest, +) +from .message import ( + AccessoryWidget, + ActionResponse, + AttachedGif, + CardWithId, + CreateMessageRequest, + DeleteMessageRequest, + Dialog, + DialogAction, + GetMessageRequest, + ListMessagesRequest, + ListMessagesResponse, + Message, + QuotedMessageMetadata, + Thread, + UpdateMessageRequest, +) +from .reaction import ( + CreateReactionRequest, + CustomEmoji, + DeleteReactionRequest, + Emoji, + EmojiReactionSummary, + ListReactionsRequest, + ListReactionsResponse, + Reaction, +) +from .slash_command import ( + SlashCommand, +) +from .space import ( + CompleteImportSpaceRequest, + CompleteImportSpaceResponse, + CreateSpaceRequest, + DeleteSpaceRequest, + FindDirectMessageRequest, + GetSpaceRequest, + ListSpacesRequest, + ListSpacesResponse, + Space, + UpdateSpaceRequest, +) +from .space_read_state import ( + GetSpaceReadStateRequest, + SpaceReadState, + UpdateSpaceReadStateRequest, +) +from .space_setup import ( + SetUpSpaceRequest, +) +from .thread_read_state import ( + GetThreadReadStateRequest, + ThreadReadState, +) +from .user import ( + User, +) +from .widgets import ( + WidgetMarkup, +) + +__all__ = ( + 'ActionStatus', + 'Annotation', + 'DriveLinkData', + 'RichLinkMetadata', + 'SlashCommandMetadata', + 'UserMentionMetadata', + 'AnnotationType', + 'Attachment', + 'AttachmentDataRef', + 'DriveDataRef', + 'GetAttachmentRequest', + 'UploadAttachmentRequest', + 'UploadAttachmentResponse', + 'ContextualAddOnMarkup', + 'DeletionMetadata', + 'Group', + 'HistoryState', + 'MatchedUrl', + 'CreateMembershipRequest', + 'DeleteMembershipRequest', + 'GetMembershipRequest', + 'ListMembershipsRequest', + 'ListMembershipsResponse', + 'Membership', + 'UpdateMembershipRequest', + 'AccessoryWidget', + 'ActionResponse', + 'AttachedGif', + 'CardWithId', + 'CreateMessageRequest', + 'DeleteMessageRequest', + 'Dialog', + 'DialogAction', + 'GetMessageRequest', + 'ListMessagesRequest', + 'ListMessagesResponse', + 'Message', + 'QuotedMessageMetadata', + 'Thread', + 'UpdateMessageRequest', + 'CreateReactionRequest', + 'CustomEmoji', + 'DeleteReactionRequest', + 'Emoji', + 'EmojiReactionSummary', + 'ListReactionsRequest', + 'ListReactionsResponse', + 'Reaction', + 'SlashCommand', + 'CompleteImportSpaceRequest', + 'CompleteImportSpaceResponse', + 'CreateSpaceRequest', + 'DeleteSpaceRequest', + 'FindDirectMessageRequest', + 'GetSpaceRequest', + 'ListSpacesRequest', + 'ListSpacesResponse', + 'Space', + 'UpdateSpaceRequest', + 'GetSpaceReadStateRequest', + 'SpaceReadState', + 'UpdateSpaceReadStateRequest', + 'SetUpSpaceRequest', + 'GetThreadReadStateRequest', + 'ThreadReadState', + 'User', + 'WidgetMarkup', +) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/action_status.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/action_status.py new file mode 100644 index 000000000000..101a433c512f --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/action_status.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.rpc import code_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.chat.v1', + manifest={ + 'ActionStatus', + }, +) + + +class ActionStatus(proto.Message): + r"""Represents the status for a request to either invoke or submit a + `dialog `__. + + Attributes: + status_code (google.rpc.code_pb2.Code): + The status code. + user_facing_message (str): + The message to send users about the status of their request. + If unset, a generic message based on the ``status_code`` is + sent. + """ + + status_code: code_pb2.Code = proto.Field( + proto.ENUM, + number=1, + enum=code_pb2.Code, + ) + user_facing_message: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/annotation.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/annotation.py new file mode 100644 index 000000000000..ddad2b85ed33 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/annotation.py @@ -0,0 +1,314 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.apps.chat_v1.types import attachment +from google.apps.chat_v1.types import user as gc_user + + +__protobuf__ = proto.module( + package='google.chat.v1', + manifest={ + 'AnnotationType', + 'Annotation', + 'UserMentionMetadata', + 'SlashCommandMetadata', + 'RichLinkMetadata', + 'DriveLinkData', + }, +) + + +class AnnotationType(proto.Enum): + r"""Type of the annotation. + + Values: + ANNOTATION_TYPE_UNSPECIFIED (0): + Default value for the enum. Don't use. + USER_MENTION (1): + A user is mentioned. + SLASH_COMMAND (2): + A slash command is invoked. + RICH_LINK (3): + A rich link annotation. + """ + ANNOTATION_TYPE_UNSPECIFIED = 0 + USER_MENTION = 1 + SLASH_COMMAND = 2 + RICH_LINK = 3 + + +class Annotation(proto.Message): + r"""Output only. Annotations associated with the plain-text body of the + message. To add basic formatting to a text message, see `Format text + messages `__. + + Example plain-text message body: + + :: + + Hello @FooBot how are you!" + + The corresponding annotations metadata: + + :: + + "annotations":[{ + "type":"USER_MENTION", + "startIndex":6, + "length":7, + "userMention": { + "user": { + "name":"users/{user}", + "displayName":"FooBot", + "avatarUrl":"https://goo.gl/aeDtrS", + "type":"BOT" + }, + "type":"MENTION" + } + }] + + 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: + type_ (google.apps.chat_v1.types.AnnotationType): + The type of this annotation. + start_index (int): + Start index (0-based, inclusive) in the + plain-text message body this annotation + corresponds to. + + This field is a member of `oneof`_ ``_start_index``. + length (int): + Length of the substring in the plain-text + message body this annotation corresponds to. + user_mention (google.apps.chat_v1.types.UserMentionMetadata): + The metadata of user mention. + + This field is a member of `oneof`_ ``metadata``. + slash_command (google.apps.chat_v1.types.SlashCommandMetadata): + The metadata for a slash command. + + This field is a member of `oneof`_ ``metadata``. + rich_link_metadata (google.apps.chat_v1.types.RichLinkMetadata): + The metadata for a rich link. + + This field is a member of `oneof`_ ``metadata``. + """ + + type_: 'AnnotationType' = proto.Field( + proto.ENUM, + number=1, + enum='AnnotationType', + ) + start_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + length: int = proto.Field( + proto.INT32, + number=3, + ) + user_mention: 'UserMentionMetadata' = proto.Field( + proto.MESSAGE, + number=4, + oneof='metadata', + message='UserMentionMetadata', + ) + slash_command: 'SlashCommandMetadata' = proto.Field( + proto.MESSAGE, + number=5, + oneof='metadata', + message='SlashCommandMetadata', + ) + rich_link_metadata: 'RichLinkMetadata' = proto.Field( + proto.MESSAGE, + number=6, + oneof='metadata', + message='RichLinkMetadata', + ) + + +class UserMentionMetadata(proto.Message): + r"""Annotation metadata for user mentions (@). + + Attributes: + user (google.apps.chat_v1.types.User): + The user mentioned. + type_ (google.apps.chat_v1.types.UserMentionMetadata.Type): + The type of user mention. + """ + class Type(proto.Enum): + r""" + + Values: + TYPE_UNSPECIFIED (0): + Default value for the enum. Don't use. + ADD (1): + Add user to space. + MENTION (2): + Mention user in space. + """ + TYPE_UNSPECIFIED = 0 + ADD = 1 + MENTION = 2 + + user: gc_user.User = proto.Field( + proto.MESSAGE, + number=1, + message=gc_user.User, + ) + type_: Type = proto.Field( + proto.ENUM, + number=2, + enum=Type, + ) + + +class SlashCommandMetadata(proto.Message): + r"""Annotation metadata for slash commands (/). + + Attributes: + bot (google.apps.chat_v1.types.User): + The Chat app whose command was invoked. + type_ (google.apps.chat_v1.types.SlashCommandMetadata.Type): + The type of slash command. + command_name (str): + The name of the invoked slash command. + command_id (int): + The command ID of the invoked slash command. + triggers_dialog (bool): + Indicates whether the slash command is for a + dialog. + """ + class Type(proto.Enum): + r""" + + Values: + TYPE_UNSPECIFIED (0): + Default value for the enum. Don't use. + ADD (1): + Add Chat app to space. + INVOKE (2): + Invoke slash command in space. + """ + TYPE_UNSPECIFIED = 0 + ADD = 1 + INVOKE = 2 + + bot: gc_user.User = proto.Field( + proto.MESSAGE, + number=1, + message=gc_user.User, + ) + type_: Type = proto.Field( + proto.ENUM, + number=2, + enum=Type, + ) + command_name: str = proto.Field( + proto.STRING, + number=3, + ) + command_id: int = proto.Field( + proto.INT64, + number=4, + ) + triggers_dialog: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class RichLinkMetadata(proto.Message): + r"""A rich link to a resource. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + uri (str): + The URI of this link. + rich_link_type (google.apps.chat_v1.types.RichLinkMetadata.RichLinkType): + The rich link type. + drive_link_data (google.apps.chat_v1.types.DriveLinkData): + Data for a drive link. + + This field is a member of `oneof`_ ``data``. + """ + class RichLinkType(proto.Enum): + r"""The rich link type. More types might be added in the future. + + Values: + RICH_LINK_TYPE_UNSPECIFIED (0): + Default value for the enum. Don't use. + DRIVE_FILE (1): + A Google Drive rich link type. + """ + RICH_LINK_TYPE_UNSPECIFIED = 0 + DRIVE_FILE = 1 + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + rich_link_type: RichLinkType = proto.Field( + proto.ENUM, + number=2, + enum=RichLinkType, + ) + drive_link_data: 'DriveLinkData' = proto.Field( + proto.MESSAGE, + number=3, + oneof='data', + message='DriveLinkData', + ) + + +class DriveLinkData(proto.Message): + r"""Data for Google Drive links. + + Attributes: + drive_data_ref (google.apps.chat_v1.types.DriveDataRef): + A + `DriveDataRef `__ + which references a Google Drive file. + mime_type (str): + The mime type of the linked Google Drive + resource. + """ + + drive_data_ref: attachment.DriveDataRef = proto.Field( + proto.MESSAGE, + number=1, + message=attachment.DriveDataRef, + ) + mime_type: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/attachment.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/attachment.py new file mode 100644 index 000000000000..0e4cb154ca91 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/attachment.py @@ -0,0 +1,228 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.chat.v1', + manifest={ + 'Attachment', + 'DriveDataRef', + 'AttachmentDataRef', + 'GetAttachmentRequest', + 'UploadAttachmentRequest', + 'UploadAttachmentResponse', + }, +) + + +class Attachment(proto.Message): + r"""An attachment in Google Chat. + + 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): + Resource name of the attachment, in the form + ``spaces/*/messages/*/attachments/*``. + content_name (str): + Output only. The original file name for the + content, not the full path. + content_type (str): + Output only. The content type (MIME type) of + the file. + attachment_data_ref (google.apps.chat_v1.types.AttachmentDataRef): + A reference to the attachment data. This + field is used with the media API to download the + attachment data. + + This field is a member of `oneof`_ ``data_ref``. + drive_data_ref (google.apps.chat_v1.types.DriveDataRef): + Output only. A reference to the Google Drive + attachment. This field is used with the Google + Drive API. + + This field is a member of `oneof`_ ``data_ref``. + thumbnail_uri (str): + Output only. The thumbnail URL which should + be used to preview the attachment to a human + user. Chat apps shouldn't use this URL to + download attachment content. + download_uri (str): + Output only. The download URL which should be + used to allow a human user to download the + attachment. Chat apps shouldn't use this URL to + download attachment content. + source (google.apps.chat_v1.types.Attachment.Source): + Output only. The source of the attachment. + """ + class Source(proto.Enum): + r"""The source of the attachment. + + Values: + SOURCE_UNSPECIFIED (0): + Reserved. + DRIVE_FILE (1): + The file is a Google Drive file. + UPLOADED_CONTENT (2): + The file is uploaded to Chat. + """ + SOURCE_UNSPECIFIED = 0 + DRIVE_FILE = 1 + UPLOADED_CONTENT = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + content_name: str = proto.Field( + proto.STRING, + number=2, + ) + content_type: str = proto.Field( + proto.STRING, + number=3, + ) + attachment_data_ref: 'AttachmentDataRef' = proto.Field( + proto.MESSAGE, + number=4, + oneof='data_ref', + message='AttachmentDataRef', + ) + drive_data_ref: 'DriveDataRef' = proto.Field( + proto.MESSAGE, + number=7, + oneof='data_ref', + message='DriveDataRef', + ) + thumbnail_uri: str = proto.Field( + proto.STRING, + number=5, + ) + download_uri: str = proto.Field( + proto.STRING, + number=6, + ) + source: Source = proto.Field( + proto.ENUM, + number=9, + enum=Source, + ) + + +class DriveDataRef(proto.Message): + r"""A reference to the data of a drive attachment. + + Attributes: + drive_file_id (str): + The ID for the drive file. Use with the Drive + API. + """ + + drive_file_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class AttachmentDataRef(proto.Message): + r"""A reference to the attachment data. + + Attributes: + resource_name (str): + The resource name of the attachment data. + This field is used with the media API to + download the attachment data. + attachment_upload_token (str): + Opaque token containing a reference to an + uploaded attachment. Treated by clients as an + opaque string and used to create or update Chat + messages with attachments. + """ + + resource_name: str = proto.Field( + proto.STRING, + number=1, + ) + attachment_upload_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetAttachmentRequest(proto.Message): + r"""Request to get an attachment. + + Attributes: + name (str): + Required. Resource name of the attachment, in the form + ``spaces/*/messages/*/attachments/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UploadAttachmentRequest(proto.Message): + r"""Request to upload an attachment. + + Attributes: + parent (str): + Required. Resource name of the Chat space in + which the attachment is uploaded. Format + "spaces/{space}". + filename (str): + Required. The filename of the attachment, + including the file extension. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filename: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UploadAttachmentResponse(proto.Message): + r"""Response of uploading an attachment. + + Attributes: + attachment_data_ref (google.apps.chat_v1.types.AttachmentDataRef): + Reference to the uploaded attachment. + """ + + attachment_data_ref: 'AttachmentDataRef' = proto.Field( + proto.MESSAGE, + number=1, + message='AttachmentDataRef', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/chat_service.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/chat_service.py new file mode 100644 index 000000000000..c5b7ceb723c4 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/chat_service.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.chat.v1', + manifest={ + }, +) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/contextual_addon.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/contextual_addon.py new file mode 100644 index 000000000000..02608fac8810 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/contextual_addon.py @@ -0,0 +1,181 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.apps.chat_v1.types import widgets as gc_widgets + + +__protobuf__ = proto.module( + package='google.chat.v1', + manifest={ + 'ContextualAddOnMarkup', + }, +) + + +class ContextualAddOnMarkup(proto.Message): + r"""The markup for developers to specify the contents of a + contextual AddOn. + + """ + + class Card(proto.Message): + r"""A card is a UI element that can contain UI widgets such as + text and images. + + Attributes: + header (google.apps.chat_v1.types.ContextualAddOnMarkup.Card.CardHeader): + The header of the card. A header usually + contains a title and an image. + sections (MutableSequence[google.apps.chat_v1.types.ContextualAddOnMarkup.Card.Section]): + Sections are separated by a line divider. + card_actions (MutableSequence[google.apps.chat_v1.types.ContextualAddOnMarkup.Card.CardAction]): + The actions of this card. + name (str): + Name of the card. + """ + + class CardHeader(proto.Message): + r""" + + Attributes: + title (str): + The title must be specified. The header has a + fixed height: if both a title and subtitle is + specified, each takes up one line. If only the + title is specified, it takes up both lines. + subtitle (str): + The subtitle of the card header. + image_style (google.apps.chat_v1.types.ContextualAddOnMarkup.Card.CardHeader.ImageStyle): + The image's type (for example, square border + or circular border). + image_url (str): + The URL of the image in the card header. + """ + class ImageStyle(proto.Enum): + r""" + + Values: + IMAGE_STYLE_UNSPECIFIED (0): + No description available. + IMAGE (1): + Square border. + AVATAR (2): + Circular border. + """ + IMAGE_STYLE_UNSPECIFIED = 0 + IMAGE = 1 + AVATAR = 2 + + title: str = proto.Field( + proto.STRING, + number=1, + ) + subtitle: str = proto.Field( + proto.STRING, + number=2, + ) + image_style: 'ContextualAddOnMarkup.Card.CardHeader.ImageStyle' = proto.Field( + proto.ENUM, + number=3, + enum='ContextualAddOnMarkup.Card.CardHeader.ImageStyle', + ) + image_url: str = proto.Field( + proto.STRING, + number=4, + ) + + class Section(proto.Message): + r"""A section contains a collection of widgets that are rendered + (vertically) in the order that they are specified. Across all + platforms, cards have a narrow fixed width, so + there's currently no need for layout properties (for example, + float). + + Attributes: + header (str): + The header of the section. Formatted text is supported. For + more information about formatting text, see `Formatting text + in Google Chat + apps `__ + and `Formatting text in Google Workspace + Add-ons `__. + widgets (MutableSequence[google.apps.chat_v1.types.WidgetMarkup]): + A section must contain at least one widget. + """ + + header: str = proto.Field( + proto.STRING, + number=1, + ) + widgets: MutableSequence[gc_widgets.WidgetMarkup] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=gc_widgets.WidgetMarkup, + ) + + class CardAction(proto.Message): + r"""A card action is + the action associated with the card. For an invoice card, a + typical action would be: delete invoice, email invoice or open + the invoice in browser. + + Not supported by Google Chat apps. + + Attributes: + action_label (str): + The label used to be displayed in the action + menu item. + on_click (google.apps.chat_v1.types.WidgetMarkup.OnClick): + The onclick action for this action item. + """ + + action_label: str = proto.Field( + proto.STRING, + number=1, + ) + on_click: gc_widgets.WidgetMarkup.OnClick = proto.Field( + proto.MESSAGE, + number=2, + message=gc_widgets.WidgetMarkup.OnClick, + ) + + header: 'ContextualAddOnMarkup.Card.CardHeader' = proto.Field( + proto.MESSAGE, + number=1, + message='ContextualAddOnMarkup.Card.CardHeader', + ) + sections: MutableSequence['ContextualAddOnMarkup.Card.Section'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='ContextualAddOnMarkup.Card.Section', + ) + card_actions: MutableSequence['ContextualAddOnMarkup.Card.CardAction'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='ContextualAddOnMarkup.Card.CardAction', + ) + name: str = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/deletion_metadata.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/deletion_metadata.py new file mode 100644 index 000000000000..7698b8fe116d --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/deletion_metadata.py @@ -0,0 +1,76 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.chat.v1', + manifest={ + 'DeletionMetadata', + }, +) + + +class DeletionMetadata(proto.Message): + r"""Information about a deleted message. A message is deleted when + ``delete_time`` is set. + + Attributes: + deletion_type (google.apps.chat_v1.types.DeletionMetadata.DeletionType): + Indicates who deleted the message. + """ + class DeletionType(proto.Enum): + r"""Who deleted the message and how it was deleted. + + Values: + DELETION_TYPE_UNSPECIFIED (0): + This value is unused. + CREATOR (1): + User deleted their own message. + SPACE_OWNER (2): + The space owner deleted the message. + ADMIN (3): + A Google Workspace admin deleted the message. + APP_MESSAGE_EXPIRY (4): + A Chat app deleted its own message when it + expired. + CREATOR_VIA_APP (5): + A Chat app deleted the message on behalf of + the user. + SPACE_OWNER_VIA_APP (6): + A Chat app deleted the message on behalf of + the space owner. + """ + DELETION_TYPE_UNSPECIFIED = 0 + CREATOR = 1 + SPACE_OWNER = 2 + ADMIN = 3 + APP_MESSAGE_EXPIRY = 4 + CREATOR_VIA_APP = 5 + SPACE_OWNER_VIA_APP = 6 + + deletion_type: DeletionType = proto.Field( + proto.ENUM, + number=1, + enum=DeletionType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/group.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/group.py new file mode 100644 index 000000000000..da8ee60dfb4d --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/group.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.chat.v1', + manifest={ + 'Group', + }, +) + + +class Group(proto.Message): + r"""A Google Group in Google Chat. + + Attributes: + name (str): + Resource name for a Google Group. + + Represents a + `group `__ + in Cloud Identity Groups API. + + Format: groups/{group} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/history_state.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/history_state.py new file mode 100644 index 000000000000..05c0f6d51721 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/history_state.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.chat.v1', + manifest={ + 'HistoryState', + }, +) + + +class HistoryState(proto.Enum): + r"""The history state for messages and spaces. Specifies how long + messages and conversation threads are kept after creation. + + Values: + HISTORY_STATE_UNSPECIFIED (0): + Default value. Do not use. + HISTORY_OFF (1): + History off. `Messages and threads are kept for 24 + hours `__. + HISTORY_ON (2): + History on. The organization's `Vault retention + rules `__ + specify for how long messages and threads are kept. + """ + HISTORY_STATE_UNSPECIFIED = 0 + HISTORY_OFF = 1 + HISTORY_ON = 2 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/matched_url.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/matched_url.py new file mode 100644 index 000000000000..329541fbbd01 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/matched_url.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.chat.v1', + manifest={ + 'MatchedUrl', + }, +) + + +class MatchedUrl(proto.Message): + r"""A matched URL in a Chat message. Chat apps can preview matched URLs. + For more information, see `Preview + links `__. + + Attributes: + url (str): + Output only. The URL that was matched. + """ + + url: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/membership.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/membership.py new file mode 100644 index 000000000000..5795df11d10c --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/membership.py @@ -0,0 +1,450 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.apps.chat_v1.types import group +from google.apps.chat_v1.types import user +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.chat.v1', + manifest={ + 'Membership', + 'CreateMembershipRequest', + 'UpdateMembershipRequest', + 'ListMembershipsRequest', + 'ListMembershipsResponse', + 'GetMembershipRequest', + 'DeleteMembershipRequest', + }, +) + + +class Membership(proto.Message): + r"""Represents a membership relation in Google Chat, such as + whether a user or Chat app is invited to, part of, or absent + from a space. + + 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): + Resource name of the membership, assigned by the server. + + Format: ``spaces/{space}/members/{member}`` + state (google.apps.chat_v1.types.Membership.MembershipState): + Output only. State of the membership. + role (google.apps.chat_v1.types.Membership.MembershipRole): + Optional. User's role within a Chat space, which determines + their permitted actions in the space. + + This field can only be used as input in + ``UpdateMembership``. + member (google.apps.chat_v1.types.User): + The Google Chat user or app the membership corresponds to. + If your Chat app `authenticates as a + user `__, + the output populates the + `user `__ + ``name`` and ``type``. + + This field is a member of `oneof`_ ``memberType``. + group_member (google.apps.chat_v1.types.Group): + The Google Group the membership corresponds + to. Only supports read operations. Other + operations, like creating or updating a + membership, aren't currently supported. + + This field is a member of `oneof`_ ``memberType``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. Immutable. The creation time of the + membership, such as when a member joined or was + invited to join a space. This field is output + only, except when used to import historical + memberships in import mode spaces. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. Immutable. The deletion time of the + membership, such as when a member left or was + removed from a space. This field is output only, + except when used to import historical + memberships in import mode spaces. + """ + class MembershipState(proto.Enum): + r"""Specifies the member's relationship with a space. Other + membership states might be supported in the future. + + Values: + MEMBERSHIP_STATE_UNSPECIFIED (0): + Default value. Don't use. + JOINED (1): + The user is added to the space, and can + participate in the space. + INVITED (2): + The user is invited to join the space, but + hasn't joined it. + NOT_A_MEMBER (3): + The user doesn't belong to the space and + doesn't have a pending invitation to join the + space. + """ + MEMBERSHIP_STATE_UNSPECIFIED = 0 + JOINED = 1 + INVITED = 2 + NOT_A_MEMBER = 3 + + class MembershipRole(proto.Enum): + r"""Represents a user's permitted actions in a Chat space. More + enum values might be added in the future. + + Values: + MEMBERSHIP_ROLE_UNSPECIFIED (0): + Default value. For + [users][google.chat.v1.Membership.member]: they aren't a + member of the space, but can be invited. For [Google + Groups][google.chat.v1.Membership.group_member]: they're + always assigned this role (other enum values might be used + in the future). + ROLE_MEMBER (1): + A member of the space. The user has basic + permissions, like sending messages to the space. + In 1:1 and unnamed group conversations, everyone + has this role. + ROLE_MANAGER (2): + A space manager. The user has all basic permissions plus + administrative permissions that let them manage the space, + like adding or removing members. Only supported in + [SpaceType.SPACE][google.chat.v1.Space.SpaceType]. + """ + MEMBERSHIP_ROLE_UNSPECIFIED = 0 + ROLE_MEMBER = 1 + ROLE_MANAGER = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: MembershipState = proto.Field( + proto.ENUM, + number=2, + enum=MembershipState, + ) + role: MembershipRole = proto.Field( + proto.ENUM, + number=7, + enum=MembershipRole, + ) + member: user.User = proto.Field( + proto.MESSAGE, + number=3, + oneof='memberType', + message=user.User, + ) + group_member: group.Group = proto.Field( + proto.MESSAGE, + number=5, + oneof='memberType', + message=group.Group, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + + +class CreateMembershipRequest(proto.Message): + r"""Request message for creating a membership. + + Attributes: + parent (str): + Required. The resource name of the space for + which to create the membership. + + Format: spaces/{space} + membership (google.apps.chat_v1.types.Membership): + Required. The membership relation to create. The + ``memberType`` field must contain a user with the + ``user.name`` and ``user.type`` fields populated. The server + will assign a resource name and overwrite anything + specified. When a Chat app creates a membership relation for + a human user, it must use the ``chat.memberships`` scope, + set ``user.type`` to ``HUMAN``, and set ``user.name`` with + format ``users/{user}``, where ``{user}`` can be the email + address for the user. For users in the same Workspace + organization ``{user}`` can also be the ``id`` of the + `person `__ + from the People API, or the ``id`` for the user in the + Directory API. For example, if the People API Person profile + ID for ``user@example.com`` is ``123456789``, you can add + the user to the space by setting the + ``membership.member.name`` to ``users/user@example.com`` or + ``users/123456789``. When a Chat app creates a membership + relation for itself, it must use the + ``chat.memberships.app`` scope, set ``user.type`` to + ``BOT``, and set ``user.name`` to ``users/app``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + membership: 'Membership' = proto.Field( + proto.MESSAGE, + number=2, + message='Membership', + ) + + +class UpdateMembershipRequest(proto.Message): + r"""Request message for updating a membership. + + Attributes: + membership (google.apps.chat_v1.types.Membership): + Required. The membership to update. Only fields specified by + ``update_mask`` are updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The field paths to update. Separate multiple + values with commas or use ``*`` to update all field paths. + + Currently supported field paths: + + - ``role`` + """ + + membership: 'Membership' = proto.Field( + proto.MESSAGE, + number=1, + message='Membership', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListMembershipsRequest(proto.Message): + r"""Request message for listing memberships. + + Attributes: + parent (str): + Required. The resource name of the space for + which to fetch a membership list. + + Format: spaces/{space} + page_size (int): + Optional. The maximum number of memberships to return. The + service might return fewer than this value. + + If unspecified, at most 100 memberships are returned. + + The maximum value is 1000. If you use a value more than + 1000, it's automatically changed to 1000. + + Negative values return an ``INVALID_ARGUMENT`` error. + page_token (str): + Optional. A page token, received from a + previous call to list memberships. Provide this + parameter to retrieve the subsequent page. + + When paginating, all other parameters provided + should match the call that provided the page + token. Passing different values to the other + parameters might lead to unexpected results. + filter (str): + Optional. A query filter. + + You can filter memberships by a member's role + (```role`` `__) + and type + (```member.type`` `__). + + To filter by role, set ``role`` to ``ROLE_MEMBER`` or + ``ROLE_MANAGER``. + + To filter by type, set ``member.type`` to ``HUMAN`` or + ``BOT``. + + To filter by both role and type, use the ``AND`` operator. + To filter by either role or type, use the ``OR`` operator. + + For example, the following queries are valid: + + :: + + role = "ROLE_MANAGER" OR role = "ROLE_MEMBER" + member.type = "HUMAN" AND role = "ROLE_MANAGER" + + The following queries are invalid: + + :: + + member.type = "HUMAN" AND member.type = "BOT" + role = "ROLE_MANAGER" AND role = "ROLE_MEMBER" + + Invalid queries are rejected by the server with an + ``INVALID_ARGUMENT`` error. + show_groups (bool): + Optional. When ``true``, also returns memberships associated + with a [Google + Group][google.chat.v1.Membership.group_member], in addition + to other types of memberships. If a + [filter][google.chat.v1.ListMembershipsRequest.filter] is + set, [Google Group][google.chat.v1.Membership.group_member] + memberships that don't match the filter criteria aren't + returned. + show_invited (bool): + Optional. When ``true``, also returns memberships associated + with + [invited][google.chat.v1.Membership.MembershipState.INVITED] + members, in addition to other types of memberships. If a + filter is set, + [invited][google.chat.v1.Membership.MembershipState.INVITED] + memberships that don't match the filter criteria aren't + returned. + + Currently requires `user + authentication `__. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=5, + ) + show_groups: bool = proto.Field( + proto.BOOL, + number=6, + ) + show_invited: bool = proto.Field( + proto.BOOL, + number=7, + ) + + +class ListMembershipsResponse(proto.Message): + r"""Response to list memberships of the space. + + Attributes: + memberships (MutableSequence[google.apps.chat_v1.types.Membership]): + Unordered list. List of memberships in the + requested (or first) page. + next_page_token (str): + A token that you can send as ``pageToken`` to retrieve the + next page of results. If empty, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + memberships: MutableSequence['Membership'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Membership', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetMembershipRequest(proto.Message): + r"""Request to get a membership of a space. + + Attributes: + name (str): + Required. Resource name of the membership to retrieve. + + To get the app's own membership, you can optionally use + ``spaces/{space}/members/app``. + + Format: ``spaces/{space}/members/{member}`` or + ``spaces/{space}/members/app`` + + When `authenticated as a + user `__, + you can use the user's email as an alias for ``{member}``. + For example, ``spaces/{space}/members/example@gmail.com`` + where ``example@gmail.com`` is the email of the Google Chat + user. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteMembershipRequest(proto.Message): + r"""Request to delete a membership in a space. + + Attributes: + name (str): + Required. Resource name of the membership to delete. Chat + apps can delete human users' or their own memberships. Chat + apps can't delete other apps' memberships. + + When deleting a human membership, requires the + ``chat.memberships`` scope and + ``spaces/{space}/members/{member}`` format. You can use the + email as an alias for ``{member}``. For example, + ``spaces/{space}/members/example@gmail.com`` where + ``example@gmail.com`` is the email of the Google Chat user. + + When deleting an app membership, requires the + ``chat.memberships.app`` scope and + ``spaces/{space}/members/app`` format. + + Format: ``spaces/{space}/members/{member}`` or + ``spaces/{space}/members/app``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/message.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/message.py new file mode 100644 index 000000000000..c0e05888aca0 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/message.py @@ -0,0 +1,1029 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.apps.card_v1.types import card as gac_card +from google.apps.chat_v1.types import action_status as gc_action_status +from google.apps.chat_v1.types import annotation +from google.apps.chat_v1.types import attachment as gc_attachment +from google.apps.chat_v1.types import contextual_addon +from google.apps.chat_v1.types import deletion_metadata as gc_deletion_metadata +from google.apps.chat_v1.types import matched_url as gc_matched_url +from google.apps.chat_v1.types import reaction +from google.apps.chat_v1.types import slash_command as gc_slash_command +from google.apps.chat_v1.types import space as gc_space +from google.apps.chat_v1.types import user +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.chat.v1', + manifest={ + 'Message', + 'AttachedGif', + 'QuotedMessageMetadata', + 'Thread', + 'ActionResponse', + 'AccessoryWidget', + 'GetMessageRequest', + 'DeleteMessageRequest', + 'UpdateMessageRequest', + 'CreateMessageRequest', + 'ListMessagesRequest', + 'ListMessagesResponse', + 'DialogAction', + 'Dialog', + 'CardWithId', + }, +) + + +class Message(proto.Message): + r"""A message in a Google Chat space. + + Attributes: + name (str): + Resource name of the message. + + Format: ``spaces/{space}/messages/{message}`` + + Where ``{space}`` is the ID of the space where the message + is posted and ``{message}`` is a system-assigned ID for the + message. For example, + ``spaces/AAAAAAAAAAA/messages/BBBBBBBBBBB.BBBBBBBBBBB``. + + If you set a custom ID when you create a message, you can + use this ID to specify the message in a request by replacing + ``{message}`` with the value from the + ``clientAssignedMessageId`` field. For example, + ``spaces/AAAAAAAAAAA/messages/client-custom-name``. For + details, see `Name a + message `__. + sender (google.apps.chat_v1.types.User): + Output only. The user who created the message. If your Chat + app `authenticates as a + user `__, + the output populates the + `user `__ + ``name`` and ``type``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. Immutable. For spaces created in + Chat, the time at which the message was created. + This field is output only, except when used in + import mode spaces. + + For import mode spaces, set this field to the + historical timestamp at which the message was + created in the source in order to preserve the + original creation time. + last_update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the message + was last edited by a user. If the message has + never been edited, this field is empty. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the message + was deleted in Google Chat. If the message is + never deleted, this field is empty. + text (str): + Plain-text body of the message. The first link to an image, + video, or web page generates a `preview + chip `__. + You can also `@mention a Google Chat + user `__, + or everyone in the space. + + To learn about creating text messages, see `Send a text + message `__. + formatted_text (str): + Output only. Contains the message ``text`` with markups + added to communicate formatting. This field might not + capture all formatting visible in the UI, but includes the + following: + + - `Markup + syntax `__ + for bold, italic, strikethrough, monospace, monospace + block, and bulleted list. + + - `User + mentions `__ + using the format ````. + + - Custom hyperlinks using the format + ``<{url}|{rendered_text}>`` where the first string is the + URL and the second is the rendered text—for example, + ````. + + - Custom emoji using the format ``:{emoji_name}:``—for + example, ``:smile:``. This doesn't apply to Unicode + emoji, such as ``U+1F600`` for a grinning face emoji. + + For more information, see `View text formatting sent in a + message `__ + cards (MutableSequence[google.apps.chat_v1.types.ContextualAddOnMarkup.Card]): + Deprecated: Use ``cards_v2`` instead. + + Rich, formatted, and interactive cards that you can use to + display UI elements such as: formatted texts, buttons, and + clickable images. Cards are normally displayed below the + plain-text body of the message. ``cards`` and ``cards_v2`` + can have a maximum size of 32 KB. + cards_v2 (MutableSequence[google.apps.chat_v1.types.CardWithId]): + An array of + `cards `__. + + Only Chat apps can create cards. If your Chat app + `authenticates as a + user `__, + the messages can't contain cards. + + To learn about cards and how to create them, see `Send card + messages `__. + + `Card + builder `__ + annotations (MutableSequence[google.apps.chat_v1.types.Annotation]): + Output only. Annotations associated with the ``text`` in + this message. + thread (google.apps.chat_v1.types.Thread): + The thread the message belongs to. For example usage, see + `Start or reply to a message + thread `__. + space (google.apps.chat_v1.types.Space): + If your Chat app `authenticates as a + user `__, + the output populates the + `space `__ + ``name``. + fallback_text (str): + A plain-text description of the message's + cards, used when the actual cards can't be + displayed—for example, mobile notifications. + action_response (google.apps.chat_v1.types.ActionResponse): + Input only. Parameters that a Chat app can + use to configure how its response is posted. + argument_text (str): + Output only. Plain-text body of the message + with all Chat app mentions stripped out. + slash_command (google.apps.chat_v1.types.SlashCommand): + Output only. Slash command information, if + applicable. + attachment (MutableSequence[google.apps.chat_v1.types.Attachment]): + User-uploaded attachment. + matched_url (google.apps.chat_v1.types.MatchedUrl): + Output only. A URL in ``spaces.messages.text`` that matches + a link preview pattern. For more information, see `Preview + links `__. + thread_reply (bool): + Output only. When ``true``, the message is a response in a + reply thread. When ``false``, the message is visible in the + space's top-level conversation as either the first message + of a thread or a message with no threaded replies. + + If the space doesn't support reply in threads, this field is + always ``false``. + client_assigned_message_id (str): + Optional. A custom ID for the message. You can use field to + identify a message, or to get, delete, or update a message. + To set a custom ID, specify the + ```messageId`` `__ + field when you create the message. For details, see `Name a + message `__. + emoji_reaction_summaries (MutableSequence[google.apps.chat_v1.types.EmojiReactionSummary]): + Output only. The list of emoji reaction + summaries on the message. + private_message_viewer (google.apps.chat_v1.types.User): + Immutable. Input for creating a message, otherwise output + only. The user that can view the message. When set, the + message is private and only visible to the specified user + and the Chat app. Link previews and attachments aren't + supported for private messages. + + Only Chat apps can send private messages. If your Chat app + `authenticates as a + user `__ + to send a message, the message can't be private and must + omit this field. + + For details, see `Send private messages to Google Chat + users `__. + deletion_metadata (google.apps.chat_v1.types.DeletionMetadata): + Output only. Information about a deleted message. A message + is deleted when ``delete_time`` is set. + quoted_message_metadata (google.apps.chat_v1.types.QuotedMessageMetadata): + Output only. Information about a message + that's quoted by a Google Chat user in a space. + Google Chat users can quote a message to reply + to it. + attached_gifs (MutableSequence[google.apps.chat_v1.types.AttachedGif]): + Output only. GIF images that are attached to + the message. + accessory_widgets (MutableSequence[google.apps.chat_v1.types.AccessoryWidget]): + One or more interactive widgets that appear at the bottom of + a message. You can add accessory widgets to messages that + contain text, cards, or both text and cards. Not supported + for messages that contain dialogs. For details, see `Add + interactive widgets at the bottom of a + message `__. + + Creating a message with accessory widgets requires [app + authentication] + (https://developers.google.com/workspace/chat/authenticate-authorize-chat-app). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + sender: user.User = proto.Field( + proto.MESSAGE, + number=2, + message=user.User, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + last_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=23, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=26, + message=timestamp_pb2.Timestamp, + ) + text: str = proto.Field( + proto.STRING, + number=4, + ) + formatted_text: str = proto.Field( + proto.STRING, + number=43, + ) + cards: MutableSequence[contextual_addon.ContextualAddOnMarkup.Card] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=contextual_addon.ContextualAddOnMarkup.Card, + ) + cards_v2: MutableSequence['CardWithId'] = proto.RepeatedField( + proto.MESSAGE, + number=22, + message='CardWithId', + ) + annotations: MutableSequence[annotation.Annotation] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=annotation.Annotation, + ) + thread: 'Thread' = proto.Field( + proto.MESSAGE, + number=11, + message='Thread', + ) + space: gc_space.Space = proto.Field( + proto.MESSAGE, + number=12, + message=gc_space.Space, + ) + fallback_text: str = proto.Field( + proto.STRING, + number=13, + ) + action_response: 'ActionResponse' = proto.Field( + proto.MESSAGE, + number=14, + message='ActionResponse', + ) + argument_text: str = proto.Field( + proto.STRING, + number=15, + ) + slash_command: gc_slash_command.SlashCommand = proto.Field( + proto.MESSAGE, + number=17, + message=gc_slash_command.SlashCommand, + ) + attachment: MutableSequence[gc_attachment.Attachment] = proto.RepeatedField( + proto.MESSAGE, + number=18, + message=gc_attachment.Attachment, + ) + matched_url: gc_matched_url.MatchedUrl = proto.Field( + proto.MESSAGE, + number=20, + message=gc_matched_url.MatchedUrl, + ) + thread_reply: bool = proto.Field( + proto.BOOL, + number=25, + ) + client_assigned_message_id: str = proto.Field( + proto.STRING, + number=32, + ) + emoji_reaction_summaries: MutableSequence[reaction.EmojiReactionSummary] = proto.RepeatedField( + proto.MESSAGE, + number=33, + message=reaction.EmojiReactionSummary, + ) + private_message_viewer: user.User = proto.Field( + proto.MESSAGE, + number=36, + message=user.User, + ) + deletion_metadata: gc_deletion_metadata.DeletionMetadata = proto.Field( + proto.MESSAGE, + number=38, + message=gc_deletion_metadata.DeletionMetadata, + ) + quoted_message_metadata: 'QuotedMessageMetadata' = proto.Field( + proto.MESSAGE, + number=39, + message='QuotedMessageMetadata', + ) + attached_gifs: MutableSequence['AttachedGif'] = proto.RepeatedField( + proto.MESSAGE, + number=42, + message='AttachedGif', + ) + accessory_widgets: MutableSequence['AccessoryWidget'] = proto.RepeatedField( + proto.MESSAGE, + number=44, + message='AccessoryWidget', + ) + + +class AttachedGif(proto.Message): + r"""A GIF image that's specified by a URL. + + Attributes: + uri (str): + Output only. The URL that hosts the GIF + image. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + + +class QuotedMessageMetadata(proto.Message): + r"""Information about a quoted message. + + Attributes: + name (str): + Output only. Resource name of the quoted message. + + Format: ``spaces/{space}/messages/{message}`` + last_update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the quoted + message was created or when the quoted message + was last updated. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + last_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class Thread(proto.Message): + r"""A thread in a Google Chat space. For example usage, see `Start or + reply to a message + thread `__. + + If you specify a thread when creating a message, you can set the + ```messageReplyOption`` `__ + field to determine what happens if no matching thread is found. + + Attributes: + name (str): + Output only. Resource name of the thread. + + Example: ``spaces/{space}/threads/{thread}`` + thread_key (str): + Optional. Input for creating or updating a thread. + Otherwise, output only. ID for the thread. Supports up to + 4000 characters. + + This ID is unique to the Chat app that sets it. For example, + if multiple Chat apps create a message using the same thread + key, the messages are posted in different threads. To reply + in a thread created by a person or another Chat app, specify + the thread ``name`` field instead. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + thread_key: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ActionResponse(proto.Message): + r"""Parameters that a Chat app can use to configure how its + response is posted. + + Attributes: + type_ (google.apps.chat_v1.types.ActionResponse.ResponseType): + Input only. The type of Chat app response. + url (str): + Input only. URL for users to authenticate or configure. + (Only for ``REQUEST_CONFIG`` response types.) + dialog_action (google.apps.chat_v1.types.DialogAction): + Input only. A response to an interaction event related to a + `dialog `__. + Must be accompanied by ``ResponseType.Dialog``. + updated_widget (google.apps.chat_v1.types.ActionResponse.UpdatedWidget): + Input only. The response of the updated + widget. + """ + class ResponseType(proto.Enum): + r"""The type of Chat app response. + + Values: + TYPE_UNSPECIFIED (0): + Default type that's handled as ``NEW_MESSAGE``. + NEW_MESSAGE (1): + Post as a new message in the topic. + UPDATE_MESSAGE (2): + Update the Chat app's message. This is only permitted on a + ``CARD_CLICKED`` event where the message sender type is + ``BOT``. + UPDATE_USER_MESSAGE_CARDS (6): + Update the cards on a user's message. This is only permitted + as a response to a ``MESSAGE`` event with a matched url, or + a ``CARD_CLICKED`` event where the message sender type is + ``HUMAN``. Text is ignored. + REQUEST_CONFIG (3): + Privately ask the user for additional + authentication or configuration. + DIALOG (4): + Presents a + `dialog `__. + UPDATE_WIDGET (7): + Widget text autocomplete options query. + """ + TYPE_UNSPECIFIED = 0 + NEW_MESSAGE = 1 + UPDATE_MESSAGE = 2 + UPDATE_USER_MESSAGE_CARDS = 6 + REQUEST_CONFIG = 3 + DIALOG = 4 + UPDATE_WIDGET = 7 + + class SelectionItems(proto.Message): + r"""List of widget autocomplete results. + + Attributes: + items (MutableSequence[google.apps.card_v1.types.SelectionInput.SelectionItem]): + An array of the SelectionItem objects. + """ + + items: MutableSequence[gac_card.SelectionInput.SelectionItem] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gac_card.SelectionInput.SelectionItem, + ) + + class UpdatedWidget(proto.Message): + r"""The response of the updated widget. + Used to provide autocomplete options for a widget. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + suggestions (google.apps.chat_v1.types.ActionResponse.SelectionItems): + List of widget autocomplete results + + This field is a member of `oneof`_ ``updated_widget``. + widget (str): + The ID of the updated widget. The ID must + match the one for the widget that triggered the + update request. + """ + + suggestions: 'ActionResponse.SelectionItems' = proto.Field( + proto.MESSAGE, + number=1, + oneof='updated_widget', + message='ActionResponse.SelectionItems', + ) + widget: str = proto.Field( + proto.STRING, + number=2, + ) + + type_: ResponseType = proto.Field( + proto.ENUM, + number=1, + enum=ResponseType, + ) + url: str = proto.Field( + proto.STRING, + number=2, + ) + dialog_action: 'DialogAction' = proto.Field( + proto.MESSAGE, + number=3, + message='DialogAction', + ) + updated_widget: UpdatedWidget = proto.Field( + proto.MESSAGE, + number=4, + message=UpdatedWidget, + ) + + +class AccessoryWidget(proto.Message): + r"""One or more interactive widgets that appear at the bottom of a + message. For details, see `Add interactive widgets at the bottom of + a + message `__. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + button_list (google.apps.card_v1.types.ButtonList): + A list of buttons. + + This field is a member of `oneof`_ ``action``. + """ + + button_list: gac_card.ButtonList = proto.Field( + proto.MESSAGE, + number=1, + oneof='action', + message=gac_card.ButtonList, + ) + + +class GetMessageRequest(proto.Message): + r"""Request to get a message. + + Attributes: + name (str): + Required. Resource name of the message. + + Format: ``spaces/{space}/messages/{message}`` + + If you've set a custom ID for your message, you can use the + value from the ``clientAssignedMessageId`` field for + ``{message}``. For details, see [Name a message] + (https://developers.google.com/workspace/chat/create-messages#name_a_created_message). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteMessageRequest(proto.Message): + r"""Request to delete a message. + + Attributes: + name (str): + Required. Resource name of the message. + + Format: ``spaces/{space}/messages/{message}`` + + If you've set a custom ID for your message, you can use the + value from the ``clientAssignedMessageId`` field for + ``{message}``. For details, see [Name a message] + (https://developers.google.com/workspace/chat/create-messages#name_a_created_message). + force (bool): + When ``true``, deleting a message also deletes its threaded + replies. When ``false``, if a message has threaded replies, + deletion fails. + + Only applies when `authenticating as a + user `__. + Has no effect when [authenticating as a Chat app] + (https://developers.google.com/workspace/chat/authenticate-authorize-chat-app). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + force: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class UpdateMessageRequest(proto.Message): + r"""Request to update a message. + + Attributes: + message (google.apps.chat_v1.types.Message): + Required. Message with fields updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The field paths to update. Separate multiple + values with commas or use ``*`` to update all field paths. + + Currently supported field paths: + + - ``text`` + + - ``attachment`` + + - ``cards`` (Requires `app + authentication `__.) + + - ``cards_v2`` (Requires `app + authentication `__.) + + - ``accessory_widgets`` (Requires `app + authentication `__.) + allow_missing (bool): + Optional. If ``true`` and the message isn't found, a new + message is created and ``updateMask`` is ignored. The + specified message ID must be + `client-assigned `__ + or the request fails. + """ + + message: 'Message' = proto.Field( + proto.MESSAGE, + number=1, + message='Message', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class CreateMessageRequest(proto.Message): + r"""Creates a message. + + Attributes: + parent (str): + Required. The resource name of the space in which to create + a message. + + Format: ``spaces/{space}`` + message (google.apps.chat_v1.types.Message): + Required. Message body. + thread_key (str): + Optional. Deprecated: Use + [thread.thread_key][google.chat.v1.Thread.thread_key] + instead. ID for the thread. Supports up to 4000 characters. + To start or add to a thread, create a message and specify a + ``threadKey`` or the + [thread.name][google.chat.v1.Thread.name]. For example + usage, see `Start or reply to a message + thread `__. + request_id (str): + Optional. A unique request ID for this + message. Specifying an existing request ID + returns the message created with that ID instead + of creating a new message. + message_reply_option (google.apps.chat_v1.types.CreateMessageRequest.MessageReplyOption): + Optional. Specifies whether a message starts + a thread or replies to one. Only supported in + named spaces. + message_id (str): + Optional. A custom ID for a message. Lets Chat apps get, + update, or delete a message without needing to store the + system-assigned ID in the message's resource name + (represented in the message ``name`` field). + + The value for this field must meet the following + requirements: + + - Begins with ``client-``. For example, + ``client-custom-name`` is a valid custom ID, but + ``custom-name`` is not. + - Contains up to 63 characters and only lowercase letters, + numbers, and hyphens. + - Is unique within a space. A Chat app can't use the same + custom ID for different messages. + + For details, see `Name a + message `__. + """ + class MessageReplyOption(proto.Enum): + r"""Specifies how to reply to a message. + More states might be added in the future. + + Values: + MESSAGE_REPLY_OPTION_UNSPECIFIED (0): + Default. Starts a new thread. Using this option ignores any + [thread ID][google.chat.v1.Thread.name] or + [``thread_key``][google.chat.v1.Thread.thread_key] that's + included. + REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD (1): + Creates the message as a reply to the thread specified by + [thread ID][google.chat.v1.Thread.name] or + [``thread_key``][google.chat.v1.Thread.thread_key]. If it + fails, the message starts a new thread instead. + REPLY_MESSAGE_OR_FAIL (2): + Creates the message as a reply to the thread specified by + [thread ID][google.chat.v1.Thread.name] or + [``thread_key``][google.chat.v1.Thread.thread_key]. If a new + ``thread_key`` is used, a new thread is created. If the + message creation fails, a ``NOT_FOUND`` error is returned + instead. + """ + MESSAGE_REPLY_OPTION_UNSPECIFIED = 0 + REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD = 1 + REPLY_MESSAGE_OR_FAIL = 2 + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + message: 'Message' = proto.Field( + proto.MESSAGE, + number=4, + message='Message', + ) + thread_key: str = proto.Field( + proto.STRING, + number=6, + ) + request_id: str = proto.Field( + proto.STRING, + number=7, + ) + message_reply_option: MessageReplyOption = proto.Field( + proto.ENUM, + number=8, + enum=MessageReplyOption, + ) + message_id: str = proto.Field( + proto.STRING, + number=9, + ) + + +class ListMessagesRequest(proto.Message): + r"""Lists messages in the specified space, that the user is a + member of. + + Attributes: + parent (str): + Required. The resource name of the space to list messages + from. + + Format: ``spaces/{space}`` + page_size (int): + The maximum number of messages returned. The service might + return fewer messages than this value. + + If unspecified, at most 25 are returned. + + The maximum value is 1000. If you use a value more than + 1000, it's automatically changed to 1000. + + Negative values return an ``INVALID_ARGUMENT`` error. + page_token (str): + Optional, if resuming from a previous query. + + A page token received from a previous list + messages call. Provide this parameter to + retrieve the subsequent page. + + When paginating, all other parameters provided + should match the call that provided the page + token. Passing different values to the other + parameters might lead to unexpected results. + filter (str): + A query filter. + + You can filter messages by date (``create_time``) and thread + (``thread.name``). + + To filter messages by the date they were created, specify + the ``create_time`` with a timestamp in + `RFC-3339 `__ format + and double quotation marks. For example, + ``"2023-04-21T11:30:00-04:00"``. You can use the greater + than operator ``>`` to list messages that were created after + a timestamp, or the less than operator ``<`` to list + messages that were created before a timestamp. To filter + messages within a time interval, use the ``AND`` operator + between two timestamps. + + To filter by thread, specify the ``thread.name``, formatted + as ``spaces/{space}/threads/{thread}``. You can only specify + one ``thread.name`` per query. + + To filter by both thread and date, use the ``AND`` operator + in your query. + + For example, the following queries are valid: + + :: + + create_time > "2012-04-21T11:30:00-04:00" + + create_time > "2012-04-21T11:30:00-04:00" AND + thread.name = spaces/AAAAAAAAAAA/threads/123 + + create_time > "2012-04-21T11:30:00+00:00" AND + + create_time < "2013-01-01T00:00:00+00:00" AND + thread.name = spaces/AAAAAAAAAAA/threads/123 + + thread.name = spaces/AAAAAAAAAAA/threads/123 + + Invalid queries are rejected by the server with an + ``INVALID_ARGUMENT`` error. + order_by (str): + Optional, if resuming from a previous query. + + How the list of messages is ordered. Specify a value to + order by an ordering operation. Valid ordering operation + values are as follows: + + - ``ASC`` for ascending. + + - ``DESC`` for descending. + + The default ordering is ``create_time ASC``. + show_deleted (bool): + Whether to include deleted messages. Deleted + messages include deleted time and metadata about + their deletion, but message content is + unavailable. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + show_deleted: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class ListMessagesResponse(proto.Message): + r"""Response message for listing messages. + + Attributes: + messages (MutableSequence[google.apps.chat_v1.types.Message]): + List of messages. + next_page_token (str): + You can send a token as ``pageToken`` to retrieve the next + page of results. If empty, there are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + messages: MutableSequence['Message'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Message', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DialogAction(proto.Message): + r"""Contains a + `dialog `__ + and request status code. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + dialog (google.apps.chat_v1.types.Dialog): + Input only. + `Dialog `__ + for the request. + + This field is a member of `oneof`_ ``action``. + action_status (google.apps.chat_v1.types.ActionStatus): + Input only. Status for a request to either invoke or submit + a + `dialog `__. + Displays a status and message to users, if necessary. For + example, in case of an error or success. + """ + + dialog: 'Dialog' = proto.Field( + proto.MESSAGE, + number=1, + oneof='action', + message='Dialog', + ) + action_status: gc_action_status.ActionStatus = proto.Field( + proto.MESSAGE, + number=2, + message=gc_action_status.ActionStatus, + ) + + +class Dialog(proto.Message): + r"""Wrapper around the card body of the dialog. + + Attributes: + body (google.apps.card_v1.types.Card): + Input only. Body of the dialog, which is rendered in a + modal. Google Chat apps don't support the following card + entities: ``DateTimePicker``, ``OnChangeAction``. + """ + + body: gac_card.Card = proto.Field( + proto.MESSAGE, + number=1, + message=gac_card.Card, + ) + + +class CardWithId(proto.Message): + r"""A + `card `__ + in a Google Chat message. + + Only Chat apps can create cards. If your Chat app `authenticates as + a + user `__, + the message can't contain cards. + + `Card builder `__ + + Attributes: + card_id (str): + Required if the message contains multiple + cards. A unique identifier for a card in a + message. + card (google.apps.card_v1.types.Card): + A card. Maximum size is 32 KB. + """ + + card_id: str = proto.Field( + proto.STRING, + number=1, + ) + card: gac_card.Card = proto.Field( + proto.MESSAGE, + number=2, + message=gac_card.Card, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/reaction.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/reaction.py new file mode 100644 index 000000000000..4117e4e24bea --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/reaction.py @@ -0,0 +1,311 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.apps.chat_v1.types import user as gc_user + + +__protobuf__ = proto.module( + package='google.chat.v1', + manifest={ + 'Reaction', + 'Emoji', + 'CustomEmoji', + 'EmojiReactionSummary', + 'CreateReactionRequest', + 'ListReactionsRequest', + 'ListReactionsResponse', + 'DeleteReactionRequest', + }, +) + + +class Reaction(proto.Message): + r"""A reaction to a message. + + Attributes: + name (str): + The resource name of the reaction. + + Format: + ``spaces/{space}/messages/{message}/reactions/{reaction}`` + user (google.apps.chat_v1.types.User): + Output only. The user who created the + reaction. + emoji (google.apps.chat_v1.types.Emoji): + The emoji used in the reaction. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + user: gc_user.User = proto.Field( + proto.MESSAGE, + number=2, + message=gc_user.User, + ) + emoji: 'Emoji' = proto.Field( + proto.MESSAGE, + number=3, + message='Emoji', + ) + + +class Emoji(proto.Message): + r"""An emoji that is used as a reaction to a message. + + 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: + unicode (str): + A basic emoji represented by a unicode + string. + + This field is a member of `oneof`_ ``content``. + custom_emoji (google.apps.chat_v1.types.CustomEmoji): + Output only. A custom emoji. + + This field is a member of `oneof`_ ``content``. + """ + + unicode: str = proto.Field( + proto.STRING, + number=1, + oneof='content', + ) + custom_emoji: 'CustomEmoji' = proto.Field( + proto.MESSAGE, + number=2, + oneof='content', + message='CustomEmoji', + ) + + +class CustomEmoji(proto.Message): + r"""Represents a custom emoji. + + Attributes: + uid (str): + Unique key for the custom emoji resource. + """ + + uid: str = proto.Field( + proto.STRING, + number=1, + ) + + +class EmojiReactionSummary(proto.Message): + r"""The number of people who reacted to a message with a specific + emoji. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + emoji (google.apps.chat_v1.types.Emoji): + Emoji associated with the reactions. + reaction_count (int): + The total number of reactions using the + associated emoji. + + This field is a member of `oneof`_ ``_reaction_count``. + """ + + emoji: 'Emoji' = proto.Field( + proto.MESSAGE, + number=1, + message='Emoji', + ) + reaction_count: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + + +class CreateReactionRequest(proto.Message): + r"""Creates a reaction to a message. + + Attributes: + parent (str): + Required. The message where the reaction is created. + + Format: ``spaces/{space}/messages/{message}`` + reaction (google.apps.chat_v1.types.Reaction): + Required. The reaction to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + reaction: 'Reaction' = proto.Field( + proto.MESSAGE, + number=2, + message='Reaction', + ) + + +class ListReactionsRequest(proto.Message): + r"""Lists reactions to a message. + + Attributes: + parent (str): + Required. The message users reacted to. + + Format: ``spaces/{space}/messages/{message}`` + page_size (int): + Optional. The maximum number of reactions + returned. The service can return fewer reactions + than this value. If unspecified, the default + value is 25. The maximum value is 200; values + above 200 are changed to 200. + page_token (str): + Optional. (If resuming from a previous + query.) + A page token received from a previous list + reactions call. Provide this to retrieve the + subsequent page. + + When paginating, the filter value should match + the call that provided the page token. Passing a + different value might lead to unexpected + results. + filter (str): + Optional. A query filter. + + You can filter reactions by + `emoji `__ + (either ``emoji.unicode`` or ``emoji.custom_emoji.uid``) and + `user `__ + (``user.name``). + + To filter reactions for multiple emojis or users, join + similar fields with the ``OR`` operator, such as + ``emoji.unicode = "🙂" OR emoji.unicode = "👍"`` and + ``user.name = "users/AAAAAA" OR user.name = "users/BBBBBB"``. + + To filter reactions by emoji and user, use the ``AND`` + operator, such as + ``emoji.unicode = "🙂" AND user.name = "users/AAAAAA"``. + + If your query uses both ``AND`` and ``OR``, group them with + parentheses. + + For example, the following queries are valid: + + :: + + user.name = "users/{user}" + emoji.unicode = "🙂" + emoji.custom_emoji.uid = "{uid}" + emoji.unicode = "🙂" OR emoji.unicode = "👍" + emoji.unicode = "🙂" OR emoji.custom_emoji.uid = "{uid}" + emoji.unicode = "🙂" AND user.name = "users/{user}" + (emoji.unicode = "🙂" OR emoji.custom_emoji.uid = "{uid}") + AND user.name = "users/{user}" + + The following queries are invalid: + + :: + + emoji.unicode = "🙂" AND emoji.unicode = "👍" + emoji.unicode = "🙂" AND emoji.custom_emoji.uid = "{uid}" + emoji.unicode = "🙂" OR user.name = "users/{user}" + emoji.unicode = "🙂" OR emoji.custom_emoji.uid = "{uid}" OR + user.name = "users/{user}" + emoji.unicode = "🙂" OR emoji.custom_emoji.uid = "{uid}" + AND user.name = "users/{user}" + + Invalid queries are rejected by the server with an + ``INVALID_ARGUMENT`` error. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListReactionsResponse(proto.Message): + r"""Response to a list reactions request. + + Attributes: + reactions (MutableSequence[google.apps.chat_v1.types.Reaction]): + List of reactions in the requested (or first) + page. + next_page_token (str): + Continuation token to retrieve the next page + of results. It's empty for the last page of + results. + """ + + @property + def raw_page(self): + return self + + reactions: MutableSequence['Reaction'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Reaction', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteReactionRequest(proto.Message): + r"""Deletes a reaction to a message. + + Attributes: + name (str): + Required. Name of the reaction to delete. + + Format: + ``spaces/{space}/messages/{message}/reactions/{reaction}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/slash_command.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/slash_command.py new file mode 100644 index 000000000000..80f38a81f085 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/slash_command.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.chat.v1', + manifest={ + 'SlashCommand', + }, +) + + +class SlashCommand(proto.Message): + r"""A `slash + command `__ + in Google Chat. + + Attributes: + command_id (int): + The ID of the slash command invoked. + """ + + command_id: int = proto.Field( + proto.INT64, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/space.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/space.py new file mode 100644 index 000000000000..b4fe3cdac30c --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/space.py @@ -0,0 +1,569 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.apps.chat_v1.types import history_state +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.chat.v1', + manifest={ + 'Space', + 'CreateSpaceRequest', + 'ListSpacesRequest', + 'ListSpacesResponse', + 'GetSpaceRequest', + 'FindDirectMessageRequest', + 'UpdateSpaceRequest', + 'DeleteSpaceRequest', + 'CompleteImportSpaceRequest', + 'CompleteImportSpaceResponse', + }, +) + + +class Space(proto.Message): + r"""A space in Google Chat. Spaces are conversations between two + or more users or 1:1 messages between a user and a Chat app. + + Attributes: + name (str): + Resource name of the space. + + Format: ``spaces/{space}`` + type_ (google.apps.chat_v1.types.Space.Type): + Output only. Deprecated: Use ``space_type`` instead. The + type of a space. + space_type (google.apps.chat_v1.types.Space.SpaceType): + The type of space. Required when creating a + space or updating the space type of a space. + Output only for other usage. + single_user_bot_dm (bool): + Optional. Whether the space is a DM between a + Chat app and a single human. + threaded (bool): + Output only. Deprecated: Use ``spaceThreadingState`` + instead. Whether messages are threaded in this space. + display_name (str): + The space's display name. Required when `creating a + space `__. + If you receive the error message ``ALREADY_EXISTS`` when + creating a space or updating the ``displayName``, try a + different ``displayName``. An existing space within the + Google Workspace organization might already use this display + name. + + For direct messages, this field might be empty. + + Supports up to 128 characters. + external_user_allowed (bool): + Immutable. Whether this space permits any Google Chat user + as a member. Input when creating a space in a Google + Workspace organization. Omit this field when creating spaces + in the following conditions: + + - The authenticated user uses a consumer account (unmanaged + user account). By default, a space created by a consumer + account permits any Google Chat user. + + - The space is used to [import data to Google Chat] + (https://developers.google.com/chat/api/guides/import-data-overview) + because import mode spaces must only permit members from + the same Google Workspace organization. However, as part + of the `Google Workspace Developer Preview + Program `__, + import mode spaces can permit any Google Chat user so + this field can then be set for import mode spaces. + + For existing spaces, this field is output only. + space_threading_state (google.apps.chat_v1.types.Space.SpaceThreadingState): + Output only. The threading state in the Chat + space. + space_details (google.apps.chat_v1.types.Space.SpaceDetails): + Details about the space including description + and rules. + space_history_state (google.apps.chat_v1.types.HistoryState): + The message history state for messages and + threads in this space. + import_mode (bool): + Optional. Whether this space is created in ``Import Mode`` + as part of a data migration into Google Workspace. While + spaces are being imported, they aren't visible to users + until the import is complete. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. Immutable. For spaces created in Chat, the time + the space was created. This field is output only, except + when used in import mode spaces. + + For import mode spaces, set this field to the historical + timestamp at which the space was created in the source in + order to preserve the original creation time. + + Only populated in the output when ``spaceType`` is + ``GROUP_CHAT`` or ``SPACE``. + admin_installed (bool): + Output only. Whether the Chat app was + installed by a Google Workspace administrator. + Administrators can install a Chat app for their + domain, organizational unit, or a group of + users. + + Administrators can only install Chat apps for + direct messaging between users and the app. To + support admin install, your app must feature + direct messaging. + """ + class Type(proto.Enum): + r"""Deprecated: Use ``SpaceType`` instead. + + Values: + TYPE_UNSPECIFIED (0): + Reserved. + ROOM (1): + Conversations between two or more humans. + DM (2): + 1:1 Direct Message between a human and a Chat + app, where all messages are flat. Note that this + doesn't include direct messages between two + humans. + """ + TYPE_UNSPECIFIED = 0 + ROOM = 1 + DM = 2 + + class SpaceType(proto.Enum): + r"""The type of space. Required when creating or updating a + space. Output only for other usage. + + Values: + SPACE_TYPE_UNSPECIFIED (0): + Reserved. + SPACE (1): + A place where people send messages, share files, and + collaborate. A ``SPACE`` can include Chat apps. + GROUP_CHAT (2): + Group conversations between 3 or more people. A + ``GROUP_CHAT`` can include Chat apps. + DIRECT_MESSAGE (3): + 1:1 messages between two humans or a human + and a Chat app. + """ + SPACE_TYPE_UNSPECIFIED = 0 + SPACE = 1 + GROUP_CHAT = 2 + DIRECT_MESSAGE = 3 + + class SpaceThreadingState(proto.Enum): + r"""Specifies the type of threading state in the Chat space. + + Values: + SPACE_THREADING_STATE_UNSPECIFIED (0): + Reserved. + THREADED_MESSAGES (2): + Named spaces that support message threads. + When users respond to a message, they can reply + in-thread, which keeps their response in the + context of the original message. + GROUPED_MESSAGES (3): + Named spaces where the conversation is + organized by topic. Topics and their replies are + grouped together. + UNTHREADED_MESSAGES (4): + Direct messages (DMs) between two people and + group conversations between 3 or more people. + """ + SPACE_THREADING_STATE_UNSPECIFIED = 0 + THREADED_MESSAGES = 2 + GROUPED_MESSAGES = 3 + UNTHREADED_MESSAGES = 4 + + class SpaceDetails(proto.Message): + r"""Details about the space including description and rules. + + Attributes: + description (str): + Optional. A description of the space. For + example, describe the space's discussion topic, + functional purpose, or participants. + + Supports up to 150 characters. + guidelines (str): + Optional. The space's rules, expectations, + and etiquette. + Supports up to 5,000 characters. + """ + + description: str = proto.Field( + proto.STRING, + number=1, + ) + guidelines: str = proto.Field( + proto.STRING, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + type_: Type = proto.Field( + proto.ENUM, + number=2, + enum=Type, + ) + space_type: SpaceType = proto.Field( + proto.ENUM, + number=10, + enum=SpaceType, + ) + single_user_bot_dm: bool = proto.Field( + proto.BOOL, + number=4, + ) + threaded: bool = proto.Field( + proto.BOOL, + number=5, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + external_user_allowed: bool = proto.Field( + proto.BOOL, + number=8, + ) + space_threading_state: SpaceThreadingState = proto.Field( + proto.ENUM, + number=9, + enum=SpaceThreadingState, + ) + space_details: SpaceDetails = proto.Field( + proto.MESSAGE, + number=11, + message=SpaceDetails, + ) + space_history_state: history_state.HistoryState = proto.Field( + proto.ENUM, + number=13, + enum=history_state.HistoryState, + ) + import_mode: bool = proto.Field( + proto.BOOL, + number=16, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=17, + message=timestamp_pb2.Timestamp, + ) + admin_installed: bool = proto.Field( + proto.BOOL, + number=19, + ) + + +class CreateSpaceRequest(proto.Message): + r"""A request to create a named space. + + Attributes: + space (google.apps.chat_v1.types.Space): + Required. The ``displayName`` and ``spaceType`` fields must + be populated. Only ``SpaceType.SPACE`` is supported. + + If you receive the error message ``ALREADY_EXISTS`` when + creating a space, try a different ``displayName``. An + existing space within the Google Workspace organization + might already use this display name. + + The space ``name`` is assigned on the server so anything + specified in this field will be ignored. + request_id (str): + Optional. A unique identifier for this + request. A random UUID is recommended. + Specifying an existing request ID returns the + space created with that ID instead of creating a + new space. + Specifying an existing request ID from the same + Chat app with a different authenticated user + returns an error. + """ + + space: 'Space' = proto.Field( + proto.MESSAGE, + number=1, + message='Space', + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListSpacesRequest(proto.Message): + r"""A request to list the spaces the caller is a member of. + + Attributes: + page_size (int): + Optional. The maximum number of spaces to return. The + service might return fewer than this value. + + If unspecified, at most 100 spaces are returned. + + The maximum value is 1000. If you use a value more than + 1000, it's automatically changed to 1000. + + Negative values return an ``INVALID_ARGUMENT`` error. + page_token (str): + Optional. A page token, received from a + previous list spaces call. Provide this + parameter to retrieve the subsequent page. + + When paginating, the filter value should match + the call that provided the page token. Passing a + different value may lead to unexpected results. + filter (str): + Optional. A query filter. + + You can filter spaces by the space type + (```space_type`` `__). + + To filter by space type, you must specify valid enum value, + such as ``SPACE`` or ``GROUP_CHAT`` (the ``space_type`` + can't be ``SPACE_TYPE_UNSPECIFIED``). To query for multiple + space types, use the ``OR`` operator. + + For example, the following queries are valid: + + :: + + space_type = "SPACE" + spaceType = "GROUP_CHAT" OR spaceType = "DIRECT_MESSAGE" + + Invalid queries are rejected by the server with an + ``INVALID_ARGUMENT`` error. + """ + + page_size: int = proto.Field( + proto.INT32, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + filter: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListSpacesResponse(proto.Message): + r"""The response for a list spaces request. + + Attributes: + spaces (MutableSequence[google.apps.chat_v1.types.Space]): + List of spaces in the requested (or first) + page. + next_page_token (str): + You can send a token as ``pageToken`` to retrieve the next + page of results. If empty, there are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + spaces: MutableSequence['Space'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Space', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetSpaceRequest(proto.Message): + r"""A request to return a single space. + + Attributes: + name (str): + Required. Resource name of the space, in the form + "spaces/*". + + Format: ``spaces/{space}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class FindDirectMessageRequest(proto.Message): + r"""A request to get direct message space based on the user + resource. + + Attributes: + name (str): + Required. Resource name of the user to find direct message + with. + + Format: ``users/{user}``, where ``{user}`` is either the + ``id`` for the + `person `__ + from the People API, or the ``id`` for the + `user `__ + in the Directory API. For example, if the People API profile + ID is ``123456789``, you can find a direct message with that + person by using ``users/123456789`` as the ``name``. When + `authenticated as a + user `__, + you can use the email as an alias for ``{user}``. For + example, ``users/example@gmail.com`` where + ``example@gmail.com`` is the email of the Google Chat user. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateSpaceRequest(proto.Message): + r"""A request to update a single space. + + Attributes: + space (google.apps.chat_v1.types.Space): + Required. Space with fields to be updated. ``Space.name`` + must be populated in the form of ``spaces/{space}``. Only + fields specified by ``update_mask`` are updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The updated field paths, comma separated if there + are multiple. + + Currently supported field paths: + + - ``display_name`` (Only supports changing the display name + of a space with the ``SPACE`` type, or when also + including the ``space_type`` mask to change a + ``GROUP_CHAT`` space type to ``SPACE``. Trying to update + the display name of a ``GROUP_CHAT`` or a + ``DIRECT_MESSAGE`` space results in an invalid argument + error. If you receive the error message + ``ALREADY_EXISTS`` when updating the ``displayName``, try + a different ``displayName``. An existing space within the + Google Workspace organization might already use this + display name.) + + - ``space_type`` (Only supports changing a ``GROUP_CHAT`` + space type to ``SPACE``. Include ``display_name`` + together with ``space_type`` in the update mask and + ensure that the specified space has a non-empty display + name and the ``SPACE`` space type. Including the + ``space_type`` mask and the ``SPACE`` type in the + specified space when updating the display name is + optional if the existing space already has the ``SPACE`` + type. Trying to update the space type in other ways + results in an invalid argument error). + + - ``space_details`` + + - ``space_history_state`` (Supports `turning history on or + off for the + space `__ + if `the organization allows users to change their history + setting `__. + Warning: mutually exclusive with all other field paths.) + + - Developer Preview: ``access_settings.audience`` (Supports + changing the `access + setting `__ + of a space. If no audience is specified in the access + setting, the space's access setting is updated to + restricted. Warning: mutually exclusive with all other + field paths.) + """ + + space: 'Space' = proto.Field( + proto.MESSAGE, + number=1, + message='Space', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteSpaceRequest(proto.Message): + r"""Request for deleting a space. + + Attributes: + name (str): + Required. Resource name of the space to delete. + + Format: ``spaces/{space}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CompleteImportSpaceRequest(proto.Message): + r"""Request message for completing the import process for a + space. + + Attributes: + name (str): + Required. Resource name of the import mode space. + + Format: ``spaces/{space}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CompleteImportSpaceResponse(proto.Message): + r"""Response message for completing the import process for a + space. + + Attributes: + space (google.apps.chat_v1.types.Space): + The import mode space. + """ + + space: 'Space' = proto.Field( + proto.MESSAGE, + number=1, + message='Space', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/space_read_state.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/space_read_state.py new file mode 100644 index 000000000000..c583db277100 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/space_read_state.py @@ -0,0 +1,145 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.chat.v1', + manifest={ + 'SpaceReadState', + 'GetSpaceReadStateRequest', + 'UpdateSpaceReadStateRequest', + }, +) + + +class SpaceReadState(proto.Message): + r"""A user's read state within a space, used to identify read and + unread messages. + + Attributes: + name (str): + Resource name of the space read state. + + Format: ``users/{user}/spaces/{space}/spaceReadState`` + last_read_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The time when the user's space read + state was updated. Usually this corresponds with + either the timestamp of the last read message, + or a timestamp specified by the user to mark the + last read position in a space. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + last_read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class GetSpaceReadStateRequest(proto.Message): + r"""Request message for GetSpaceReadState API. + + Attributes: + name (str): + Required. Resource name of the space read state to retrieve. + + Only supports getting read state for the calling user. + + To refer to the calling user, set one of the following: + + - The ``me`` alias. For example, + ``users/me/spaces/{space}/spaceReadState``. + + - Their Workspace email address. For example, + ``users/user@example.com/spaces/{space}/spaceReadState``. + + - Their user id. For example, + ``users/123456789/spaces/{space}/spaceReadState``. + + Format: users/{user}/spaces/{space}/spaceReadState + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateSpaceReadStateRequest(proto.Message): + r"""Request message for UpdateSpaceReadState API. + + Attributes: + space_read_state (google.apps.chat_v1.types.SpaceReadState): + Required. The space read state and fields to update. + + Only supports updating read state for the calling user. + + To refer to the calling user, set one of the following: + + - The ``me`` alias. For example, + ``users/me/spaces/{space}/spaceReadState``. + + - Their Workspace email address. For example, + ``users/user@example.com/spaces/{space}/spaceReadState``. + + - Their user id. For example, + ``users/123456789/spaces/{space}/spaceReadState``. + + Format: users/{user}/spaces/{space}/spaceReadState + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The field paths to update. Currently supported + field paths: + + - ``last_read_time`` + + When the ``last_read_time`` is before the latest message + create time, the space appears as unread in the UI. + + To mark the space as read, set ``last_read_time`` to any + value later (larger) than the latest message create time. + The ``last_read_time`` is coerced to match the latest + message create time. Note that the space read state only + affects the read state of messages that are visible in the + space's top-level conversation. Replies in threads are + unaffected by this timestamp, and instead rely on the thread + read state. + """ + + space_read_state: 'SpaceReadState' = proto.Field( + proto.MESSAGE, + number=1, + message='SpaceReadState', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/space_setup.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/space_setup.py new file mode 100644 index 000000000000..de192e68bb0b --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/space_setup.py @@ -0,0 +1,121 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.apps.chat_v1.types import membership +from google.apps.chat_v1.types import space as gc_space + + +__protobuf__ = proto.module( + package='google.chat.v1', + manifest={ + 'SetUpSpaceRequest', + }, +) + + +class SetUpSpaceRequest(proto.Message): + r"""Request to create a space and add specified users to it. + + Attributes: + space (google.apps.chat_v1.types.Space): + Required. The ``Space.spaceType`` field is required. + + To create a space, set ``Space.spaceType`` to ``SPACE`` and + set ``Space.displayName``. If you receive the error message + ``ALREADY_EXISTS`` when setting up a space, try a different + ``displayName``. An existing space within the Google + Workspace organization might already use this display name. + + To create a group chat, set ``Space.spaceType`` to + ``GROUP_CHAT``. Don't set ``Space.displayName``. + + To create a 1:1 conversation between humans, set + ``Space.spaceType`` to ``DIRECT_MESSAGE`` and set + ``Space.singleUserBotDm`` to ``false``. Don't set + ``Space.displayName`` or ``Space.spaceDetails``. + + To create an 1:1 conversation between a human and the + calling Chat app, set ``Space.spaceType`` to + ``DIRECT_MESSAGE`` and ``Space.singleUserBotDm`` to + ``true``. Don't set ``Space.displayName`` or + ``Space.spaceDetails``. + + If a ``DIRECT_MESSAGE`` space already exists, that space is + returned instead of creating a new space. + request_id (str): + Optional. A unique identifier for this + request. A random UUID is recommended. + Specifying an existing request ID returns the + space created with that ID instead of creating a + new space. + Specifying an existing request ID from the same + Chat app with a different authenticated user + returns an error. + memberships (MutableSequence[google.apps.chat_v1.types.Membership]): + Optional. The Google Chat users to invite to join the space. + Omit the calling user, as they are added automatically. + + The set currently allows up to 20 memberships (in addition + to the caller). + + The ``Membership.member`` field must contain a ``user`` with + ``name`` populated (format: ``users/{user}``) and ``type`` + set to ``User.Type.HUMAN``. You can only add human users + when setting up a space (adding Chat apps is only supported + for direct message setup with the calling app). You can also + add members using the user's email as an alias for {user}. + For example, the ``user.name`` can be + ``users/example@gmail.com``." To invite Gmail users or users + from external Google Workspace domains, user's email must be + used for ``{user}``. + + Optional when setting ``Space.spaceType`` to ``SPACE``. + + Required when setting ``Space.spaceType`` to ``GROUP_CHAT``, + along with at least two memberships. + + Required when setting ``Space.spaceType`` to + ``DIRECT_MESSAGE`` with a human user, along with exactly one + membership. + + Must be empty when creating a 1:1 conversation between a + human and the calling Chat app (when setting + ``Space.spaceType`` to ``DIRECT_MESSAGE`` and + ``Space.singleUserBotDm`` to ``true``). + """ + + space: gc_space.Space = proto.Field( + proto.MESSAGE, + number=1, + message=gc_space.Space, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + memberships: MutableSequence[membership.Membership] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=membership.Membership, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/thread_read_state.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/thread_read_state.py new file mode 100644 index 000000000000..5f44d9226be1 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/thread_read_state.py @@ -0,0 +1,92 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.chat.v1', + manifest={ + 'ThreadReadState', + 'GetThreadReadStateRequest', + }, +) + + +class ThreadReadState(proto.Message): + r"""A user's read state within a thread, used to identify read + and unread messages. + + Attributes: + name (str): + Resource name of the thread read state. + + Format: + ``users/{user}/spaces/{space}/threads/{thread}/threadReadState`` + last_read_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the user's thread read state + was updated. Usually this corresponds with the + timestamp of the last read message in a thread. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + last_read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class GetThreadReadStateRequest(proto.Message): + r"""Request message for GetThreadReadStateRequest API. + + Attributes: + name (str): + Required. Resource name of the thread read state to + retrieve. + + Only supports getting read state for the calling user. + + To refer to the calling user, set one of the following: + + - The ``me`` alias. For example, + ``users/me/spaces/{space}/threads/{thread}/threadReadState``. + + - Their Workspace email address. For example, + ``users/user@example.com/spaces/{space}/threads/{thread}/threadReadState``. + + - Their user id. For example, + ``users/123456789/spaces/{space}/threads/{thread}/threadReadState``. + + Format: + users/{user}/spaces/{space}/threads/{thread}/threadReadState + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/user.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/user.py new file mode 100644 index 000000000000..00a7b263f4ad --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/user.py @@ -0,0 +1,115 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.chat.v1', + manifest={ + 'User', + }, +) + + +class User(proto.Message): + r"""A user in Google Chat. When returned as an output from a request, if + your Chat app `authenticates as a + user `__, + the output for a ``User`` resource only populates the user's + ``name`` and ``type``. + + Attributes: + name (str): + Resource name for a Google Chat [user][google.chat.v1.User]. + + Format: ``users/{user}``. ``users/app`` can be used as an + alias for the calling app + [bot][google.chat.v1.User.Type.BOT] user. + + For [human users][google.chat.v1.User.Type.HUMAN], + ``{user}`` is the same user identifier as: + + - the ``id`` for the + `Person `__ + in the People API. For example, ``users/123456789`` in + Chat API represents the same person as the ``123456789`` + Person profile ID in People API. + + - the ``id`` for a + `user `__ + in the Admin SDK Directory API. + + - the user's email address can be used as an alias for + ``{user}`` in API requests. For example, if the People + API Person profile ID for ``user@example.com`` is + ``123456789``, you can use ``users/user@example.com`` as + an alias to reference ``users/123456789``. Only the + canonical resource name (for example ``users/123456789``) + will be returned from the API. + display_name (str): + Output only. The user's display name. + domain_id (str): + Unique identifier of the user's Google + Workspace domain. + type_ (google.apps.chat_v1.types.User.Type): + User type. + is_anonymous (bool): + Output only. When ``true``, the user is deleted or their + profile is not visible. + """ + class Type(proto.Enum): + r""" + + Values: + TYPE_UNSPECIFIED (0): + Default value for the enum. DO NOT USE. + HUMAN (1): + Human user. + BOT (2): + Chat app user. + """ + TYPE_UNSPECIFIED = 0 + HUMAN = 1 + BOT = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + domain_id: str = proto.Field( + proto.STRING, + number=6, + ) + type_: Type = proto.Field( + proto.ENUM, + number=5, + enum=Type, + ) + is_anonymous: bool = proto.Field( + proto.BOOL, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/widgets.py b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/widgets.py new file mode 100644 index 000000000000..bde8ff6ad3dc --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/google/apps/chat_v1/types/widgets.py @@ -0,0 +1,527 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.chat.v1', + manifest={ + 'WidgetMarkup', + }, +) + + +class WidgetMarkup(proto.Message): + r"""A widget is a UI element that presents text and images. + + 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_paragraph (google.apps.chat_v1.types.WidgetMarkup.TextParagraph): + Display a text paragraph in this widget. + + This field is a member of `oneof`_ ``data``. + image (google.apps.chat_v1.types.WidgetMarkup.Image): + Display an image in this widget. + + This field is a member of `oneof`_ ``data``. + key_value (google.apps.chat_v1.types.WidgetMarkup.KeyValue): + Display a key value item in this widget. + + This field is a member of `oneof`_ ``data``. + buttons (MutableSequence[google.apps.chat_v1.types.WidgetMarkup.Button]): + A list of buttons. Buttons is also ``oneof data`` and only + one of these fields should be set. + """ + class Icon(proto.Enum): + r"""The set of supported icons. + + Values: + ICON_UNSPECIFIED (0): + No description available. + AIRPLANE (1): + No description available. + BOOKMARK (26): + No description available. + BUS (25): + No description available. + CAR (9): + No description available. + CLOCK (2): + No description available. + CONFIRMATION_NUMBER_ICON (12): + No description available. + DOLLAR (14): + No description available. + DESCRIPTION (27): + No description available. + EMAIL (10): + No description available. + EVENT_PERFORMER (20): + No description available. + EVENT_SEAT (21): + No description available. + FLIGHT_ARRIVAL (16): + No description available. + FLIGHT_DEPARTURE (15): + No description available. + HOTEL (6): + No description available. + HOTEL_ROOM_TYPE (17): + No description available. + INVITE (19): + No description available. + MAP_PIN (3): + No description available. + MEMBERSHIP (24): + No description available. + MULTIPLE_PEOPLE (18): + No description available. + OFFER (30): + No description available. + PERSON (11): + No description available. + PHONE (13): + No description available. + RESTAURANT_ICON (7): + No description available. + SHOPPING_CART (8): + No description available. + STAR (5): + No description available. + STORE (22): + No description available. + TICKET (4): + No description available. + TRAIN (23): + No description available. + VIDEO_CAMERA (28): + No description available. + VIDEO_PLAY (29): + No description available. + """ + ICON_UNSPECIFIED = 0 + AIRPLANE = 1 + BOOKMARK = 26 + BUS = 25 + CAR = 9 + CLOCK = 2 + CONFIRMATION_NUMBER_ICON = 12 + DOLLAR = 14 + DESCRIPTION = 27 + EMAIL = 10 + EVENT_PERFORMER = 20 + EVENT_SEAT = 21 + FLIGHT_ARRIVAL = 16 + FLIGHT_DEPARTURE = 15 + HOTEL = 6 + HOTEL_ROOM_TYPE = 17 + INVITE = 19 + MAP_PIN = 3 + MEMBERSHIP = 24 + MULTIPLE_PEOPLE = 18 + OFFER = 30 + PERSON = 11 + PHONE = 13 + RESTAURANT_ICON = 7 + SHOPPING_CART = 8 + STAR = 5 + STORE = 22 + TICKET = 4 + TRAIN = 23 + VIDEO_CAMERA = 28 + VIDEO_PLAY = 29 + + class TextParagraph(proto.Message): + r"""A paragraph of text. Formatted text supported. For more information + about formatting text, see `Formatting text in Google Chat + apps `__ + and `Formatting text in Google Workspace + Add-ons `__. + + Attributes: + text (str): + + """ + + text: str = proto.Field( + proto.STRING, + number=1, + ) + + class Button(proto.Message): + r"""A button. Can be a text button or an image button. + + 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_button (google.apps.chat_v1.types.WidgetMarkup.TextButton): + A button with text and ``onclick`` action. + + This field is a member of `oneof`_ ``type``. + image_button (google.apps.chat_v1.types.WidgetMarkup.ImageButton): + A button with image and ``onclick`` action. + + This field is a member of `oneof`_ ``type``. + """ + + text_button: 'WidgetMarkup.TextButton' = proto.Field( + proto.MESSAGE, + number=1, + oneof='type', + message='WidgetMarkup.TextButton', + ) + image_button: 'WidgetMarkup.ImageButton' = proto.Field( + proto.MESSAGE, + number=2, + oneof='type', + message='WidgetMarkup.ImageButton', + ) + + class TextButton(proto.Message): + r"""A button with text and ``onclick`` action. + + Attributes: + text (str): + The text of the button. + on_click (google.apps.chat_v1.types.WidgetMarkup.OnClick): + The ``onclick`` action of the button. + """ + + text: str = proto.Field( + proto.STRING, + number=1, + ) + on_click: 'WidgetMarkup.OnClick' = proto.Field( + proto.MESSAGE, + number=2, + message='WidgetMarkup.OnClick', + ) + + class KeyValue(proto.Message): + r"""A UI element contains a key (label) and a value (content). This + element can also contain some actions such as ``onclick`` button. + + 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: + icon (google.apps.chat_v1.types.WidgetMarkup.Icon): + An enum value that's replaced by the Chat API + with the corresponding icon image. + + This field is a member of `oneof`_ ``icons``. + icon_url (str): + The icon specified by a URL. + + This field is a member of `oneof`_ ``icons``. + top_label (str): + The text of the top label. Formatted text supported. For + more information about formatting text, see `Formatting text + in Google Chat + apps `__ + and `Formatting text in Google Workspace + Add-ons `__. + content (str): + The text of the content. Formatted text supported and always + required. For more information about formatting text, see + `Formatting text in Google Chat + apps `__ + and `Formatting text in Google Workspace + Add-ons `__. + content_multiline (bool): + If the content should be multiline. + bottom_label (str): + The text of the bottom label. Formatted text supported. For + more information about formatting text, see `Formatting text + in Google Chat + apps `__ + and `Formatting text in Google Workspace + Add-ons `__. + on_click (google.apps.chat_v1.types.WidgetMarkup.OnClick): + The ``onclick`` action. Only the top label, bottom label, + and content region are clickable. + button (google.apps.chat_v1.types.WidgetMarkup.Button): + A button that can be clicked to trigger an + action. + + This field is a member of `oneof`_ ``control``. + """ + + icon: 'WidgetMarkup.Icon' = proto.Field( + proto.ENUM, + number=1, + oneof='icons', + enum='WidgetMarkup.Icon', + ) + icon_url: str = proto.Field( + proto.STRING, + number=2, + oneof='icons', + ) + top_label: str = proto.Field( + proto.STRING, + number=3, + ) + content: str = proto.Field( + proto.STRING, + number=4, + ) + content_multiline: bool = proto.Field( + proto.BOOL, + number=9, + ) + bottom_label: str = proto.Field( + proto.STRING, + number=5, + ) + on_click: 'WidgetMarkup.OnClick' = proto.Field( + proto.MESSAGE, + number=6, + message='WidgetMarkup.OnClick', + ) + button: 'WidgetMarkup.Button' = proto.Field( + proto.MESSAGE, + number=7, + oneof='control', + message='WidgetMarkup.Button', + ) + + class Image(proto.Message): + r"""An image that's specified by a URL and can have an ``onclick`` + action. + + Attributes: + image_url (str): + The URL of the image. + on_click (google.apps.chat_v1.types.WidgetMarkup.OnClick): + The ``onclick`` action. + aspect_ratio (float): + The aspect ratio of this image (width and + height). This field lets you reserve the right + height for the image while waiting for it to + load. It's not meant to override the built-in + aspect ratio of the image. If unset, the server + fills it by prefetching the image. + """ + + image_url: str = proto.Field( + proto.STRING, + number=1, + ) + on_click: 'WidgetMarkup.OnClick' = proto.Field( + proto.MESSAGE, + number=2, + message='WidgetMarkup.OnClick', + ) + aspect_ratio: float = proto.Field( + proto.DOUBLE, + number=3, + ) + + class ImageButton(proto.Message): + r"""An image button with an ``onclick`` action. + + 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: + icon (google.apps.chat_v1.types.WidgetMarkup.Icon): + The icon specified by an ``enum`` that indices to an icon + provided by Chat API. + + This field is a member of `oneof`_ ``icons``. + icon_url (str): + The icon specified by a URL. + + This field is a member of `oneof`_ ``icons``. + on_click (google.apps.chat_v1.types.WidgetMarkup.OnClick): + The ``onclick`` action. + name (str): + The name of this ``image_button`` that's used for + accessibility. Default value is provided if this name isn't + specified. + """ + + icon: 'WidgetMarkup.Icon' = proto.Field( + proto.ENUM, + number=1, + oneof='icons', + enum='WidgetMarkup.Icon', + ) + icon_url: str = proto.Field( + proto.STRING, + number=3, + oneof='icons', + ) + on_click: 'WidgetMarkup.OnClick' = proto.Field( + proto.MESSAGE, + number=2, + message='WidgetMarkup.OnClick', + ) + name: str = proto.Field( + proto.STRING, + number=4, + ) + + class OnClick(proto.Message): + r"""An ``onclick`` action (for example, open a link). + + 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: + action (google.apps.chat_v1.types.WidgetMarkup.FormAction): + A form action is triggered by this ``onclick`` action if + specified. + + This field is a member of `oneof`_ ``data``. + open_link (google.apps.chat_v1.types.WidgetMarkup.OpenLink): + This ``onclick`` action triggers an open link action if + specified. + + This field is a member of `oneof`_ ``data``. + """ + + action: 'WidgetMarkup.FormAction' = proto.Field( + proto.MESSAGE, + number=1, + oneof='data', + message='WidgetMarkup.FormAction', + ) + open_link: 'WidgetMarkup.OpenLink' = proto.Field( + proto.MESSAGE, + number=2, + oneof='data', + message='WidgetMarkup.OpenLink', + ) + + class OpenLink(proto.Message): + r"""A link that opens a new window. + + Attributes: + url (str): + The URL to open. + """ + + url: str = proto.Field( + proto.STRING, + number=1, + ) + + class FormAction(proto.Message): + r"""A form action describes the behavior when the form is + submitted. For example, you can invoke Apps Script to handle the + form. + + Attributes: + action_method_name (str): + The method name is used to identify which + part of the form triggered the form submission. + This information is echoed back to the Chat app + as part of the card click event. You can use the + same method name for several elements that + trigger a common behavior. + parameters (MutableSequence[google.apps.chat_v1.types.WidgetMarkup.FormAction.ActionParameter]): + List of action parameters. + """ + + class ActionParameter(proto.Message): + r"""List of string parameters to supply when the action method is + invoked. For example, consider three snooze buttons: snooze now, + snooze one day, snooze next week. You might use + ``action method = snooze()``, passing the snooze type and snooze + time in the list of string parameters. + + Attributes: + key (str): + The name of the parameter for the action + script. + value (str): + The value of the parameter. + """ + + key: str = proto.Field( + proto.STRING, + number=1, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + + action_method_name: str = proto.Field( + proto.STRING, + number=1, + ) + parameters: MutableSequence['WidgetMarkup.FormAction.ActionParameter'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='WidgetMarkup.FormAction.ActionParameter', + ) + + text_paragraph: TextParagraph = proto.Field( + proto.MESSAGE, + number=1, + oneof='data', + message=TextParagraph, + ) + image: Image = proto.Field( + proto.MESSAGE, + number=2, + oneof='data', + message=Image, + ) + key_value: KeyValue = proto.Field( + proto.MESSAGE, + number=3, + oneof='data', + message=KeyValue, + ) + buttons: MutableSequence[Button] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=Button, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-apps-chat/v1/mypy.ini b/owl-bot-staging/google-apps-chat/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-apps-chat/v1/noxfile.py b/owl-bot-staging/google-apps-chat/v1/noxfile.py new file mode 100644 index 000000000000..860d8405c589 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/noxfile.py @@ -0,0 +1,253 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import re +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12" +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-apps-chat' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.12" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/apps/chat_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + +@nox.session(python=ALL_PYTHON[-1]) +def prerelease_deps(session): + """Run the unit test suite against pre-release versions of dependencies.""" + + # Install test environment dependencies + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + + # Install the package without dependencies + session.install('-e', '.', '--no-deps') + + # We test the minimum dependency versions using the minimum Python + # version so the lowest python runtime that we test has a corresponding constraints + # file, located at `testing/constraints--.txt`, which contains all of the + # dependencies and extras. + with open( + CURRENT_DIRECTORY + / "testing" + / f"constraints-{ALL_PYTHON[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + "grpcio", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + + session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run( + "python", "-c", "import proto; print(proto.__version__)" + ) + + session.run( + 'py.test', + '--quiet', + '--cov=google/apps/chat_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '-p', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_complete_import_space_async.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_complete_import_space_async.py new file mode 100644 index 000000000000..eb3d8ad74c09 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_complete_import_space_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CompleteImportSpace +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_CompleteImportSpace_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_complete_import_space(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.CompleteImportSpaceRequest( + name="name_value", + ) + + # Make the request + response = await client.complete_import_space(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_CompleteImportSpace_async] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_complete_import_space_sync.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_complete_import_space_sync.py new file mode 100644 index 000000000000..f0407dcdfe08 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_complete_import_space_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CompleteImportSpace +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_CompleteImportSpace_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_complete_import_space(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.CompleteImportSpaceRequest( + name="name_value", + ) + + # Make the request + response = client.complete_import_space(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_CompleteImportSpace_sync] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_create_membership_async.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_create_membership_async.py new file mode 100644 index 000000000000..60566b393ded --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_create_membership_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateMembership +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_CreateMembership_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_create_membership(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.CreateMembershipRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_membership(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_CreateMembership_async] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_create_membership_sync.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_create_membership_sync.py new file mode 100644 index 000000000000..b62a644f1f32 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_create_membership_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateMembership +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_CreateMembership_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_create_membership(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.CreateMembershipRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_membership(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_CreateMembership_sync] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_create_message_async.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_create_message_async.py new file mode 100644 index 000000000000..72ba6415f63c --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_create_message_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateMessage +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_CreateMessage_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_create_message(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.CreateMessageRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_message(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_CreateMessage_async] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_create_message_sync.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_create_message_sync.py new file mode 100644 index 000000000000..c44ca5ca7c61 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_create_message_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateMessage +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_CreateMessage_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_create_message(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.CreateMessageRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_message(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_CreateMessage_sync] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_create_reaction_async.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_create_reaction_async.py new file mode 100644 index 000000000000..11207c61d5a5 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_create_reaction_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateReaction +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_CreateReaction_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_create_reaction(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.CreateReactionRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_reaction(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_CreateReaction_async] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_create_reaction_sync.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_create_reaction_sync.py new file mode 100644 index 000000000000..fc0a1dcbfa71 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_create_reaction_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateReaction +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_CreateReaction_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_create_reaction(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.CreateReactionRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_reaction(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_CreateReaction_sync] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_create_space_async.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_create_space_async.py new file mode 100644 index 000000000000..047b4031cee0 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_create_space_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSpace +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_CreateSpace_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_create_space(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.CreateSpaceRequest( + ) + + # Make the request + response = await client.create_space(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_CreateSpace_async] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_create_space_sync.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_create_space_sync.py new file mode 100644 index 000000000000..845ce548ddc0 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_create_space_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSpace +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_CreateSpace_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_create_space(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.CreateSpaceRequest( + ) + + # Make the request + response = client.create_space(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_CreateSpace_sync] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_delete_membership_async.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_delete_membership_async.py new file mode 100644 index 000000000000..3f70072ab861 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_delete_membership_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteMembership +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_DeleteMembership_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_delete_membership(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.DeleteMembershipRequest( + name="name_value", + ) + + # Make the request + response = await client.delete_membership(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_DeleteMembership_async] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_delete_membership_sync.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_delete_membership_sync.py new file mode 100644 index 000000000000..314ad62b04f8 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_delete_membership_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteMembership +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_DeleteMembership_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_delete_membership(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.DeleteMembershipRequest( + name="name_value", + ) + + # Make the request + response = client.delete_membership(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_DeleteMembership_sync] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_delete_message_async.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_delete_message_async.py new file mode 100644 index 000000000000..08b0e0fa6ba3 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_delete_message_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteMessage +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_DeleteMessage_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_delete_message(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.DeleteMessageRequest( + name="name_value", + ) + + # Make the request + await client.delete_message(request=request) + + +# [END chat_v1_generated_ChatService_DeleteMessage_async] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_delete_message_sync.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_delete_message_sync.py new file mode 100644 index 000000000000..83dd784b1400 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_delete_message_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteMessage +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_DeleteMessage_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_delete_message(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.DeleteMessageRequest( + name="name_value", + ) + + # Make the request + client.delete_message(request=request) + + +# [END chat_v1_generated_ChatService_DeleteMessage_sync] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_delete_reaction_async.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_delete_reaction_async.py new file mode 100644 index 000000000000..9c7540493984 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_delete_reaction_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteReaction +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_DeleteReaction_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_delete_reaction(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.DeleteReactionRequest( + name="name_value", + ) + + # Make the request + await client.delete_reaction(request=request) + + +# [END chat_v1_generated_ChatService_DeleteReaction_async] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_delete_reaction_sync.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_delete_reaction_sync.py new file mode 100644 index 000000000000..21fb22ffa7d5 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_delete_reaction_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteReaction +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_DeleteReaction_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_delete_reaction(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.DeleteReactionRequest( + name="name_value", + ) + + # Make the request + client.delete_reaction(request=request) + + +# [END chat_v1_generated_ChatService_DeleteReaction_sync] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_delete_space_async.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_delete_space_async.py new file mode 100644 index 000000000000..571abb07384b --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_delete_space_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSpace +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_DeleteSpace_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_delete_space(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.DeleteSpaceRequest( + name="name_value", + ) + + # Make the request + await client.delete_space(request=request) + + +# [END chat_v1_generated_ChatService_DeleteSpace_async] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_delete_space_sync.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_delete_space_sync.py new file mode 100644 index 000000000000..0308f1882724 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_delete_space_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSpace +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_DeleteSpace_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_delete_space(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.DeleteSpaceRequest( + name="name_value", + ) + + # Make the request + client.delete_space(request=request) + + +# [END chat_v1_generated_ChatService_DeleteSpace_sync] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_find_direct_message_async.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_find_direct_message_async.py new file mode 100644 index 000000000000..dea2614bc880 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_find_direct_message_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FindDirectMessage +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_FindDirectMessage_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_find_direct_message(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.FindDirectMessageRequest( + name="name_value", + ) + + # Make the request + response = await client.find_direct_message(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_FindDirectMessage_async] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_find_direct_message_sync.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_find_direct_message_sync.py new file mode 100644 index 000000000000..0d362f304c72 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_find_direct_message_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FindDirectMessage +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_FindDirectMessage_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_find_direct_message(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.FindDirectMessageRequest( + name="name_value", + ) + + # Make the request + response = client.find_direct_message(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_FindDirectMessage_sync] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_attachment_async.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_attachment_async.py new file mode 100644 index 000000000000..d25b554098f5 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_attachment_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAttachment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_GetAttachment_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_get_attachment(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.GetAttachmentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_attachment(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_GetAttachment_async] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_attachment_sync.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_attachment_sync.py new file mode 100644 index 000000000000..ca283f3c124f --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_attachment_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAttachment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_GetAttachment_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_get_attachment(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.GetAttachmentRequest( + name="name_value", + ) + + # Make the request + response = client.get_attachment(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_GetAttachment_sync] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_membership_async.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_membership_async.py new file mode 100644 index 000000000000..68b8c087718e --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_membership_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetMembership +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_GetMembership_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_get_membership(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.GetMembershipRequest( + name="name_value", + ) + + # Make the request + response = await client.get_membership(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_GetMembership_async] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_membership_sync.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_membership_sync.py new file mode 100644 index 000000000000..6b411d8238b2 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_membership_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetMembership +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_GetMembership_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_get_membership(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.GetMembershipRequest( + name="name_value", + ) + + # Make the request + response = client.get_membership(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_GetMembership_sync] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_message_async.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_message_async.py new file mode 100644 index 000000000000..f26a26633c9a --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_message_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetMessage +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_GetMessage_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_get_message(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.GetMessageRequest( + name="name_value", + ) + + # Make the request + response = await client.get_message(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_GetMessage_async] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_message_sync.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_message_sync.py new file mode 100644 index 000000000000..e65714297a3a --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_message_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetMessage +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_GetMessage_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_get_message(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.GetMessageRequest( + name="name_value", + ) + + # Make the request + response = client.get_message(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_GetMessage_sync] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_space_async.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_space_async.py new file mode 100644 index 000000000000..0719a19c9ed9 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_space_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSpace +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_GetSpace_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_get_space(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.GetSpaceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_space(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_GetSpace_async] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_space_read_state_async.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_space_read_state_async.py new file mode 100644 index 000000000000..00e9802d128c --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_space_read_state_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSpaceReadState +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_GetSpaceReadState_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_get_space_read_state(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.GetSpaceReadStateRequest( + name="name_value", + ) + + # Make the request + response = await client.get_space_read_state(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_GetSpaceReadState_async] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_space_read_state_sync.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_space_read_state_sync.py new file mode 100644 index 000000000000..e31628bfe083 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_space_read_state_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSpaceReadState +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_GetSpaceReadState_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_get_space_read_state(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.GetSpaceReadStateRequest( + name="name_value", + ) + + # Make the request + response = client.get_space_read_state(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_GetSpaceReadState_sync] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_space_sync.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_space_sync.py new file mode 100644 index 000000000000..1dcfe9923b65 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_space_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSpace +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_GetSpace_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_get_space(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.GetSpaceRequest( + name="name_value", + ) + + # Make the request + response = client.get_space(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_GetSpace_sync] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_thread_read_state_async.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_thread_read_state_async.py new file mode 100644 index 000000000000..e3e583d2c0e6 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_thread_read_state_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetThreadReadState +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_GetThreadReadState_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_get_thread_read_state(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.GetThreadReadStateRequest( + name="name_value", + ) + + # Make the request + response = await client.get_thread_read_state(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_GetThreadReadState_async] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_thread_read_state_sync.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_thread_read_state_sync.py new file mode 100644 index 000000000000..cbc17b5887d9 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_get_thread_read_state_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetThreadReadState +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_GetThreadReadState_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_get_thread_read_state(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.GetThreadReadStateRequest( + name="name_value", + ) + + # Make the request + response = client.get_thread_read_state(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_GetThreadReadState_sync] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_list_memberships_async.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_list_memberships_async.py new file mode 100644 index 000000000000..4dc65c2dc96c --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_list_memberships_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMemberships +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_ListMemberships_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_list_memberships(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.ListMembershipsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_memberships(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END chat_v1_generated_ChatService_ListMemberships_async] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_list_memberships_sync.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_list_memberships_sync.py new file mode 100644 index 000000000000..22e0921f817e --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_list_memberships_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMemberships +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_ListMemberships_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_list_memberships(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.ListMembershipsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_memberships(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END chat_v1_generated_ChatService_ListMemberships_sync] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_list_messages_async.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_list_messages_async.py new file mode 100644 index 000000000000..5371a27e6f61 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_list_messages_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMessages +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_ListMessages_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_list_messages(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.ListMessagesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_messages(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END chat_v1_generated_ChatService_ListMessages_async] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_list_messages_sync.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_list_messages_sync.py new file mode 100644 index 000000000000..8219d306faac --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_list_messages_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMessages +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_ListMessages_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_list_messages(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.ListMessagesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_messages(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END chat_v1_generated_ChatService_ListMessages_sync] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_list_reactions_async.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_list_reactions_async.py new file mode 100644 index 000000000000..0e8ee42218d3 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_list_reactions_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListReactions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_ListReactions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_list_reactions(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.ListReactionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_reactions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END chat_v1_generated_ChatService_ListReactions_async] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_list_reactions_sync.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_list_reactions_sync.py new file mode 100644 index 000000000000..f0eeb49736b9 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_list_reactions_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListReactions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_ListReactions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_list_reactions(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.ListReactionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_reactions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END chat_v1_generated_ChatService_ListReactions_sync] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_list_spaces_async.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_list_spaces_async.py new file mode 100644 index 000000000000..09b7b2e20cf3 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_list_spaces_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSpaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_ListSpaces_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_list_spaces(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.ListSpacesRequest( + ) + + # Make the request + page_result = client.list_spaces(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END chat_v1_generated_ChatService_ListSpaces_async] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_list_spaces_sync.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_list_spaces_sync.py new file mode 100644 index 000000000000..11329278cccc --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_list_spaces_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSpaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_ListSpaces_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_list_spaces(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.ListSpacesRequest( + ) + + # Make the request + page_result = client.list_spaces(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END chat_v1_generated_ChatService_ListSpaces_sync] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_set_up_space_async.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_set_up_space_async.py new file mode 100644 index 000000000000..6870b8744a05 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_set_up_space_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetUpSpace +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_SetUpSpace_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_set_up_space(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.SetUpSpaceRequest( + ) + + # Make the request + response = await client.set_up_space(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_SetUpSpace_async] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_set_up_space_sync.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_set_up_space_sync.py new file mode 100644 index 000000000000..4d27131a243c --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_set_up_space_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetUpSpace +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_SetUpSpace_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_set_up_space(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.SetUpSpaceRequest( + ) + + # Make the request + response = client.set_up_space(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_SetUpSpace_sync] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_update_membership_async.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_update_membership_async.py new file mode 100644 index 000000000000..99143b9d193f --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_update_membership_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMembership +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_UpdateMembership_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_update_membership(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.UpdateMembershipRequest( + ) + + # Make the request + response = await client.update_membership(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_UpdateMembership_async] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_update_membership_sync.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_update_membership_sync.py new file mode 100644 index 000000000000..fad015860782 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_update_membership_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMembership +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_UpdateMembership_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_update_membership(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.UpdateMembershipRequest( + ) + + # Make the request + response = client.update_membership(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_UpdateMembership_sync] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_update_message_async.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_update_message_async.py new file mode 100644 index 000000000000..cdcd3af09dd1 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_update_message_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMessage +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_UpdateMessage_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_update_message(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.UpdateMessageRequest( + ) + + # Make the request + response = await client.update_message(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_UpdateMessage_async] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_update_message_sync.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_update_message_sync.py new file mode 100644 index 000000000000..b7662e0ddf8f --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_update_message_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMessage +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_UpdateMessage_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_update_message(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.UpdateMessageRequest( + ) + + # Make the request + response = client.update_message(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_UpdateMessage_sync] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_update_space_async.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_update_space_async.py new file mode 100644 index 000000000000..14e0944aaaeb --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_update_space_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSpace +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_UpdateSpace_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_update_space(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.UpdateSpaceRequest( + ) + + # Make the request + response = await client.update_space(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_UpdateSpace_async] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_update_space_read_state_async.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_update_space_read_state_async.py new file mode 100644 index 000000000000..6ef56226e616 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_update_space_read_state_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSpaceReadState +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_UpdateSpaceReadState_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_update_space_read_state(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.UpdateSpaceReadStateRequest( + ) + + # Make the request + response = await client.update_space_read_state(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_UpdateSpaceReadState_async] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_update_space_read_state_sync.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_update_space_read_state_sync.py new file mode 100644 index 000000000000..ee5effca33af --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_update_space_read_state_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSpaceReadState +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_UpdateSpaceReadState_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_update_space_read_state(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.UpdateSpaceReadStateRequest( + ) + + # Make the request + response = client.update_space_read_state(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_UpdateSpaceReadState_sync] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_update_space_sync.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_update_space_sync.py new file mode 100644 index 000000000000..a5158f7a9e07 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_update_space_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSpace +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_UpdateSpace_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_update_space(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.UpdateSpaceRequest( + ) + + # Make the request + response = client.update_space(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_UpdateSpace_sync] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_upload_attachment_async.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_upload_attachment_async.py new file mode 100644 index 000000000000..d9bc0a25a595 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_upload_attachment_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UploadAttachment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_UploadAttachment_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_upload_attachment(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.UploadAttachmentRequest( + parent="parent_value", + filename="filename_value", + ) + + # Make the request + response = await client.upload_attachment(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_UploadAttachment_async] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_upload_attachment_sync.py b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_upload_attachment_sync.py new file mode 100644 index 000000000000..01c590369be5 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/chat_v1_generated_chat_service_upload_attachment_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UploadAttachment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_UploadAttachment_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_upload_attachment(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.UploadAttachmentRequest( + parent="parent_value", + filename="filename_value", + ) + + # Make the request + response = client.upload_attachment(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_UploadAttachment_sync] diff --git a/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/snippet_metadata_google.chat.v1.json b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/snippet_metadata_google.chat.v1.json new file mode 100644 index 000000000000..4d9054689b87 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/samples/generated_samples/snippet_metadata_google.chat.v1.json @@ -0,0 +1,4207 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.chat.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-apps-chat", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.complete_import_space", + "method": { + "fullName": "google.chat.v1.ChatService.CompleteImportSpace", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "CompleteImportSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.CompleteImportSpaceRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.CompleteImportSpaceResponse", + "shortName": "complete_import_space" + }, + "description": "Sample for CompleteImportSpace", + "file": "chat_v1_generated_chat_service_complete_import_space_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_CompleteImportSpace_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_complete_import_space_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.complete_import_space", + "method": { + "fullName": "google.chat.v1.ChatService.CompleteImportSpace", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "CompleteImportSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.CompleteImportSpaceRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.CompleteImportSpaceResponse", + "shortName": "complete_import_space" + }, + "description": "Sample for CompleteImportSpace", + "file": "chat_v1_generated_chat_service_complete_import_space_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_CompleteImportSpace_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_complete_import_space_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.create_membership", + "method": { + "fullName": "google.chat.v1.ChatService.CreateMembership", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "CreateMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.CreateMembershipRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "membership", + "type": "google.apps.chat_v1.types.Membership" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Membership", + "shortName": "create_membership" + }, + "description": "Sample for CreateMembership", + "file": "chat_v1_generated_chat_service_create_membership_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_CreateMembership_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_create_membership_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.create_membership", + "method": { + "fullName": "google.chat.v1.ChatService.CreateMembership", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "CreateMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.CreateMembershipRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "membership", + "type": "google.apps.chat_v1.types.Membership" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Membership", + "shortName": "create_membership" + }, + "description": "Sample for CreateMembership", + "file": "chat_v1_generated_chat_service_create_membership_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_CreateMembership_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_create_membership_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.create_message", + "method": { + "fullName": "google.chat.v1.ChatService.CreateMessage", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "CreateMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.CreateMessageRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "message", + "type": "google.apps.chat_v1.types.Message" + }, + { + "name": "message_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Message", + "shortName": "create_message" + }, + "description": "Sample for CreateMessage", + "file": "chat_v1_generated_chat_service_create_message_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_CreateMessage_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_create_message_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.create_message", + "method": { + "fullName": "google.chat.v1.ChatService.CreateMessage", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "CreateMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.CreateMessageRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "message", + "type": "google.apps.chat_v1.types.Message" + }, + { + "name": "message_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Message", + "shortName": "create_message" + }, + "description": "Sample for CreateMessage", + "file": "chat_v1_generated_chat_service_create_message_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_CreateMessage_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_create_message_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.create_reaction", + "method": { + "fullName": "google.chat.v1.ChatService.CreateReaction", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "CreateReaction" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.CreateReactionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "reaction", + "type": "google.apps.chat_v1.types.Reaction" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Reaction", + "shortName": "create_reaction" + }, + "description": "Sample for CreateReaction", + "file": "chat_v1_generated_chat_service_create_reaction_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_CreateReaction_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_create_reaction_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.create_reaction", + "method": { + "fullName": "google.chat.v1.ChatService.CreateReaction", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "CreateReaction" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.CreateReactionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "reaction", + "type": "google.apps.chat_v1.types.Reaction" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Reaction", + "shortName": "create_reaction" + }, + "description": "Sample for CreateReaction", + "file": "chat_v1_generated_chat_service_create_reaction_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_CreateReaction_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_create_reaction_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.create_space", + "method": { + "fullName": "google.chat.v1.ChatService.CreateSpace", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "CreateSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.CreateSpaceRequest" + }, + { + "name": "space", + "type": "google.apps.chat_v1.types.Space" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Space", + "shortName": "create_space" + }, + "description": "Sample for CreateSpace", + "file": "chat_v1_generated_chat_service_create_space_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_CreateSpace_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_create_space_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.create_space", + "method": { + "fullName": "google.chat.v1.ChatService.CreateSpace", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "CreateSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.CreateSpaceRequest" + }, + { + "name": "space", + "type": "google.apps.chat_v1.types.Space" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Space", + "shortName": "create_space" + }, + "description": "Sample for CreateSpace", + "file": "chat_v1_generated_chat_service_create_space_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_CreateSpace_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_create_space_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.delete_membership", + "method": { + "fullName": "google.chat.v1.ChatService.DeleteMembership", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "DeleteMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.DeleteMembershipRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Membership", + "shortName": "delete_membership" + }, + "description": "Sample for DeleteMembership", + "file": "chat_v1_generated_chat_service_delete_membership_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_DeleteMembership_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_delete_membership_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.delete_membership", + "method": { + "fullName": "google.chat.v1.ChatService.DeleteMembership", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "DeleteMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.DeleteMembershipRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Membership", + "shortName": "delete_membership" + }, + "description": "Sample for DeleteMembership", + "file": "chat_v1_generated_chat_service_delete_membership_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_DeleteMembership_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_delete_membership_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.delete_message", + "method": { + "fullName": "google.chat.v1.ChatService.DeleteMessage", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "DeleteMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.DeleteMessageRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_message" + }, + "description": "Sample for DeleteMessage", + "file": "chat_v1_generated_chat_service_delete_message_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_DeleteMessage_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_delete_message_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.delete_message", + "method": { + "fullName": "google.chat.v1.ChatService.DeleteMessage", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "DeleteMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.DeleteMessageRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_message" + }, + "description": "Sample for DeleteMessage", + "file": "chat_v1_generated_chat_service_delete_message_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_DeleteMessage_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_delete_message_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.delete_reaction", + "method": { + "fullName": "google.chat.v1.ChatService.DeleteReaction", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "DeleteReaction" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.DeleteReactionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_reaction" + }, + "description": "Sample for DeleteReaction", + "file": "chat_v1_generated_chat_service_delete_reaction_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_DeleteReaction_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_delete_reaction_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.delete_reaction", + "method": { + "fullName": "google.chat.v1.ChatService.DeleteReaction", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "DeleteReaction" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.DeleteReactionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_reaction" + }, + "description": "Sample for DeleteReaction", + "file": "chat_v1_generated_chat_service_delete_reaction_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_DeleteReaction_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_delete_reaction_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.delete_space", + "method": { + "fullName": "google.chat.v1.ChatService.DeleteSpace", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "DeleteSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.DeleteSpaceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_space" + }, + "description": "Sample for DeleteSpace", + "file": "chat_v1_generated_chat_service_delete_space_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_DeleteSpace_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_delete_space_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.delete_space", + "method": { + "fullName": "google.chat.v1.ChatService.DeleteSpace", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "DeleteSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.DeleteSpaceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_space" + }, + "description": "Sample for DeleteSpace", + "file": "chat_v1_generated_chat_service_delete_space_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_DeleteSpace_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_delete_space_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.find_direct_message", + "method": { + "fullName": "google.chat.v1.ChatService.FindDirectMessage", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "FindDirectMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.FindDirectMessageRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Space", + "shortName": "find_direct_message" + }, + "description": "Sample for FindDirectMessage", + "file": "chat_v1_generated_chat_service_find_direct_message_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_FindDirectMessage_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_find_direct_message_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.find_direct_message", + "method": { + "fullName": "google.chat.v1.ChatService.FindDirectMessage", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "FindDirectMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.FindDirectMessageRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Space", + "shortName": "find_direct_message" + }, + "description": "Sample for FindDirectMessage", + "file": "chat_v1_generated_chat_service_find_direct_message_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_FindDirectMessage_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_find_direct_message_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.get_attachment", + "method": { + "fullName": "google.chat.v1.ChatService.GetAttachment", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "GetAttachment" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.GetAttachmentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Attachment", + "shortName": "get_attachment" + }, + "description": "Sample for GetAttachment", + "file": "chat_v1_generated_chat_service_get_attachment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_GetAttachment_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_get_attachment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.get_attachment", + "method": { + "fullName": "google.chat.v1.ChatService.GetAttachment", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "GetAttachment" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.GetAttachmentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Attachment", + "shortName": "get_attachment" + }, + "description": "Sample for GetAttachment", + "file": "chat_v1_generated_chat_service_get_attachment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_GetAttachment_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_get_attachment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.get_membership", + "method": { + "fullName": "google.chat.v1.ChatService.GetMembership", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "GetMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.GetMembershipRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Membership", + "shortName": "get_membership" + }, + "description": "Sample for GetMembership", + "file": "chat_v1_generated_chat_service_get_membership_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_GetMembership_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_get_membership_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.get_membership", + "method": { + "fullName": "google.chat.v1.ChatService.GetMembership", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "GetMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.GetMembershipRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Membership", + "shortName": "get_membership" + }, + "description": "Sample for GetMembership", + "file": "chat_v1_generated_chat_service_get_membership_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_GetMembership_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_get_membership_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.get_message", + "method": { + "fullName": "google.chat.v1.ChatService.GetMessage", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "GetMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.GetMessageRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Message", + "shortName": "get_message" + }, + "description": "Sample for GetMessage", + "file": "chat_v1_generated_chat_service_get_message_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_GetMessage_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_get_message_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.get_message", + "method": { + "fullName": "google.chat.v1.ChatService.GetMessage", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "GetMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.GetMessageRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Message", + "shortName": "get_message" + }, + "description": "Sample for GetMessage", + "file": "chat_v1_generated_chat_service_get_message_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_GetMessage_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_get_message_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.get_space_read_state", + "method": { + "fullName": "google.chat.v1.ChatService.GetSpaceReadState", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "GetSpaceReadState" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.GetSpaceReadStateRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.SpaceReadState", + "shortName": "get_space_read_state" + }, + "description": "Sample for GetSpaceReadState", + "file": "chat_v1_generated_chat_service_get_space_read_state_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_GetSpaceReadState_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_get_space_read_state_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.get_space_read_state", + "method": { + "fullName": "google.chat.v1.ChatService.GetSpaceReadState", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "GetSpaceReadState" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.GetSpaceReadStateRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.SpaceReadState", + "shortName": "get_space_read_state" + }, + "description": "Sample for GetSpaceReadState", + "file": "chat_v1_generated_chat_service_get_space_read_state_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_GetSpaceReadState_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_get_space_read_state_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.get_space", + "method": { + "fullName": "google.chat.v1.ChatService.GetSpace", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "GetSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.GetSpaceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Space", + "shortName": "get_space" + }, + "description": "Sample for GetSpace", + "file": "chat_v1_generated_chat_service_get_space_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_GetSpace_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_get_space_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.get_space", + "method": { + "fullName": "google.chat.v1.ChatService.GetSpace", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "GetSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.GetSpaceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Space", + "shortName": "get_space" + }, + "description": "Sample for GetSpace", + "file": "chat_v1_generated_chat_service_get_space_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_GetSpace_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_get_space_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.get_thread_read_state", + "method": { + "fullName": "google.chat.v1.ChatService.GetThreadReadState", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "GetThreadReadState" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.GetThreadReadStateRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.ThreadReadState", + "shortName": "get_thread_read_state" + }, + "description": "Sample for GetThreadReadState", + "file": "chat_v1_generated_chat_service_get_thread_read_state_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_GetThreadReadState_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_get_thread_read_state_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.get_thread_read_state", + "method": { + "fullName": "google.chat.v1.ChatService.GetThreadReadState", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "GetThreadReadState" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.GetThreadReadStateRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.ThreadReadState", + "shortName": "get_thread_read_state" + }, + "description": "Sample for GetThreadReadState", + "file": "chat_v1_generated_chat_service_get_thread_read_state_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_GetThreadReadState_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_get_thread_read_state_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.list_memberships", + "method": { + "fullName": "google.chat.v1.ChatService.ListMemberships", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "ListMemberships" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.ListMembershipsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.services.chat_service.pagers.ListMembershipsAsyncPager", + "shortName": "list_memberships" + }, + "description": "Sample for ListMemberships", + "file": "chat_v1_generated_chat_service_list_memberships_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_ListMemberships_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_list_memberships_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.list_memberships", + "method": { + "fullName": "google.chat.v1.ChatService.ListMemberships", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "ListMemberships" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.ListMembershipsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.services.chat_service.pagers.ListMembershipsPager", + "shortName": "list_memberships" + }, + "description": "Sample for ListMemberships", + "file": "chat_v1_generated_chat_service_list_memberships_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_ListMemberships_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_list_memberships_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.list_messages", + "method": { + "fullName": "google.chat.v1.ChatService.ListMessages", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "ListMessages" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.ListMessagesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.services.chat_service.pagers.ListMessagesAsyncPager", + "shortName": "list_messages" + }, + "description": "Sample for ListMessages", + "file": "chat_v1_generated_chat_service_list_messages_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_ListMessages_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_list_messages_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.list_messages", + "method": { + "fullName": "google.chat.v1.ChatService.ListMessages", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "ListMessages" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.ListMessagesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.services.chat_service.pagers.ListMessagesPager", + "shortName": "list_messages" + }, + "description": "Sample for ListMessages", + "file": "chat_v1_generated_chat_service_list_messages_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_ListMessages_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_list_messages_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.list_reactions", + "method": { + "fullName": "google.chat.v1.ChatService.ListReactions", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "ListReactions" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.ListReactionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.services.chat_service.pagers.ListReactionsAsyncPager", + "shortName": "list_reactions" + }, + "description": "Sample for ListReactions", + "file": "chat_v1_generated_chat_service_list_reactions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_ListReactions_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_list_reactions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.list_reactions", + "method": { + "fullName": "google.chat.v1.ChatService.ListReactions", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "ListReactions" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.ListReactionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.services.chat_service.pagers.ListReactionsPager", + "shortName": "list_reactions" + }, + "description": "Sample for ListReactions", + "file": "chat_v1_generated_chat_service_list_reactions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_ListReactions_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_list_reactions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.list_spaces", + "method": { + "fullName": "google.chat.v1.ChatService.ListSpaces", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "ListSpaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.ListSpacesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.services.chat_service.pagers.ListSpacesAsyncPager", + "shortName": "list_spaces" + }, + "description": "Sample for ListSpaces", + "file": "chat_v1_generated_chat_service_list_spaces_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_ListSpaces_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_list_spaces_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.list_spaces", + "method": { + "fullName": "google.chat.v1.ChatService.ListSpaces", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "ListSpaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.ListSpacesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.services.chat_service.pagers.ListSpacesPager", + "shortName": "list_spaces" + }, + "description": "Sample for ListSpaces", + "file": "chat_v1_generated_chat_service_list_spaces_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_ListSpaces_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_list_spaces_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.set_up_space", + "method": { + "fullName": "google.chat.v1.ChatService.SetUpSpace", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "SetUpSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.SetUpSpaceRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Space", + "shortName": "set_up_space" + }, + "description": "Sample for SetUpSpace", + "file": "chat_v1_generated_chat_service_set_up_space_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_SetUpSpace_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_set_up_space_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.set_up_space", + "method": { + "fullName": "google.chat.v1.ChatService.SetUpSpace", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "SetUpSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.SetUpSpaceRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Space", + "shortName": "set_up_space" + }, + "description": "Sample for SetUpSpace", + "file": "chat_v1_generated_chat_service_set_up_space_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_SetUpSpace_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_set_up_space_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.update_membership", + "method": { + "fullName": "google.chat.v1.ChatService.UpdateMembership", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "UpdateMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.UpdateMembershipRequest" + }, + { + "name": "membership", + "type": "google.apps.chat_v1.types.Membership" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Membership", + "shortName": "update_membership" + }, + "description": "Sample for UpdateMembership", + "file": "chat_v1_generated_chat_service_update_membership_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_UpdateMembership_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_update_membership_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.update_membership", + "method": { + "fullName": "google.chat.v1.ChatService.UpdateMembership", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "UpdateMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.UpdateMembershipRequest" + }, + { + "name": "membership", + "type": "google.apps.chat_v1.types.Membership" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Membership", + "shortName": "update_membership" + }, + "description": "Sample for UpdateMembership", + "file": "chat_v1_generated_chat_service_update_membership_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_UpdateMembership_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_update_membership_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.update_message", + "method": { + "fullName": "google.chat.v1.ChatService.UpdateMessage", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "UpdateMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.UpdateMessageRequest" + }, + { + "name": "message", + "type": "google.apps.chat_v1.types.Message" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Message", + "shortName": "update_message" + }, + "description": "Sample for UpdateMessage", + "file": "chat_v1_generated_chat_service_update_message_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_UpdateMessage_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_update_message_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.update_message", + "method": { + "fullName": "google.chat.v1.ChatService.UpdateMessage", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "UpdateMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.UpdateMessageRequest" + }, + { + "name": "message", + "type": "google.apps.chat_v1.types.Message" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Message", + "shortName": "update_message" + }, + "description": "Sample for UpdateMessage", + "file": "chat_v1_generated_chat_service_update_message_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_UpdateMessage_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_update_message_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.update_space_read_state", + "method": { + "fullName": "google.chat.v1.ChatService.UpdateSpaceReadState", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "UpdateSpaceReadState" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.UpdateSpaceReadStateRequest" + }, + { + "name": "space_read_state", + "type": "google.apps.chat_v1.types.SpaceReadState" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.SpaceReadState", + "shortName": "update_space_read_state" + }, + "description": "Sample for UpdateSpaceReadState", + "file": "chat_v1_generated_chat_service_update_space_read_state_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_UpdateSpaceReadState_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_update_space_read_state_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.update_space_read_state", + "method": { + "fullName": "google.chat.v1.ChatService.UpdateSpaceReadState", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "UpdateSpaceReadState" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.UpdateSpaceReadStateRequest" + }, + { + "name": "space_read_state", + "type": "google.apps.chat_v1.types.SpaceReadState" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.SpaceReadState", + "shortName": "update_space_read_state" + }, + "description": "Sample for UpdateSpaceReadState", + "file": "chat_v1_generated_chat_service_update_space_read_state_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_UpdateSpaceReadState_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_update_space_read_state_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.update_space", + "method": { + "fullName": "google.chat.v1.ChatService.UpdateSpace", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "UpdateSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.UpdateSpaceRequest" + }, + { + "name": "space", + "type": "google.apps.chat_v1.types.Space" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Space", + "shortName": "update_space" + }, + "description": "Sample for UpdateSpace", + "file": "chat_v1_generated_chat_service_update_space_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_UpdateSpace_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_update_space_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.update_space", + "method": { + "fullName": "google.chat.v1.ChatService.UpdateSpace", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "UpdateSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.UpdateSpaceRequest" + }, + { + "name": "space", + "type": "google.apps.chat_v1.types.Space" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Space", + "shortName": "update_space" + }, + "description": "Sample for UpdateSpace", + "file": "chat_v1_generated_chat_service_update_space_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_UpdateSpace_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_update_space_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.upload_attachment", + "method": { + "fullName": "google.chat.v1.ChatService.UploadAttachment", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "UploadAttachment" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.UploadAttachmentRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.UploadAttachmentResponse", + "shortName": "upload_attachment" + }, + "description": "Sample for UploadAttachment", + "file": "chat_v1_generated_chat_service_upload_attachment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_UploadAttachment_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_upload_attachment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.upload_attachment", + "method": { + "fullName": "google.chat.v1.ChatService.UploadAttachment", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "UploadAttachment" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.UploadAttachmentRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.UploadAttachmentResponse", + "shortName": "upload_attachment" + }, + "description": "Sample for UploadAttachment", + "file": "chat_v1_generated_chat_service_upload_attachment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_UploadAttachment_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_upload_attachment_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-apps-chat/v1/scripts/fixup_chat_v1_keywords.py b/owl-bot-staging/google-apps-chat/v1/scripts/fixup_chat_v1_keywords.py new file mode 100644 index 000000000000..ba4a80893a22 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/scripts/fixup_chat_v1_keywords.py @@ -0,0 +1,201 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class chatCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'complete_import_space': ('name', ), + 'create_membership': ('parent', 'membership', ), + 'create_message': ('parent', 'message', 'thread_key', 'request_id', 'message_reply_option', 'message_id', ), + 'create_reaction': ('parent', 'reaction', ), + 'create_space': ('space', 'request_id', ), + 'delete_membership': ('name', ), + 'delete_message': ('name', 'force', ), + 'delete_reaction': ('name', ), + 'delete_space': ('name', ), + 'find_direct_message': ('name', ), + 'get_attachment': ('name', ), + 'get_membership': ('name', ), + 'get_message': ('name', ), + 'get_space': ('name', ), + 'get_space_read_state': ('name', ), + 'get_thread_read_state': ('name', ), + 'list_memberships': ('parent', 'page_size', 'page_token', 'filter', 'show_groups', 'show_invited', ), + 'list_messages': ('parent', 'page_size', 'page_token', 'filter', 'order_by', 'show_deleted', ), + 'list_reactions': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_spaces': ('page_size', 'page_token', 'filter', ), + 'set_up_space': ('space', 'request_id', 'memberships', ), + 'update_membership': ('membership', 'update_mask', ), + 'update_message': ('message', 'update_mask', 'allow_missing', ), + 'update_space': ('space', 'update_mask', ), + 'update_space_read_state': ('space_read_state', 'update_mask', ), + 'upload_attachment': ('parent', 'filename', ), + } + + 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=chatCallTransformer(), +): + """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 chat client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-apps-chat/v1/setup.py b/owl-bot-staging/google-apps-chat/v1/setup.py new file mode 100644 index 000000000000..7226fe90982f --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/setup.py @@ -0,0 +1,94 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-apps-chat' + + +description = "Google Apps Chat API client library" + +version = None + +with open(os.path.join(package_root, 'google/apps/chat/gapic_version.py')) as fp: + version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) + assert (len(version_candidates) == 1) + version = version_candidates[0] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + "google-apps-card >= 0.1.0, <1.0.0dev", +] +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-chat" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.find_namespace_packages() + if package.startswith("google") +] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-apps-chat/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-apps-chat/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..78d32650e218 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/testing/constraints-3.10.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-apps-card diff --git a/owl-bot-staging/google-apps-chat/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-apps-chat/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..78d32650e218 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/testing/constraints-3.11.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-apps-card diff --git a/owl-bot-staging/google-apps-chat/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-apps-chat/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..78d32650e218 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/testing/constraints-3.12.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-apps-card diff --git a/owl-bot-staging/google-apps-chat/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-apps-chat/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..b0fe42ddc60f --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/testing/constraints-3.7.txt @@ -0,0 +1,11 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.1 +google-auth==2.14.1 +proto-plus==1.22.3 +protobuf==3.19.5 +google-apps-card==0.1.0 diff --git a/owl-bot-staging/google-apps-chat/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-apps-chat/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..78d32650e218 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/testing/constraints-3.8.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-apps-card diff --git a/owl-bot-staging/google-apps-chat/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-apps-chat/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..78d32650e218 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/testing/constraints-3.9.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-apps-card diff --git a/owl-bot-staging/google-apps-chat/v1/tests/__init__.py b/owl-bot-staging/google-apps-chat/v1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-apps-chat/v1/tests/unit/__init__.py b/owl-bot-staging/google-apps-chat/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-apps-chat/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-apps-chat/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-apps-chat/v1/tests/unit/gapic/chat_v1/__init__.py b/owl-bot-staging/google-apps-chat/v1/tests/unit/gapic/chat_v1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/tests/unit/gapic/chat_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-apps-chat/v1/tests/unit/gapic/chat_v1/test_chat_service.py b/owl-bot-staging/google-apps-chat/v1/tests/unit/gapic/chat_v1/test_chat_service.py new file mode 100644 index 000000000000..4cfefd5fab1e --- /dev/null +++ b/owl-bot-staging/google-apps-chat/v1/tests/unit/gapic/chat_v1/test_chat_service.py @@ -0,0 +1,16352 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.apps.card_v1.types import card +from google.apps.chat_v1.services.chat_service import ChatServiceAsyncClient +from google.apps.chat_v1.services.chat_service import ChatServiceClient +from google.apps.chat_v1.services.chat_service import pagers +from google.apps.chat_v1.services.chat_service import transports +from google.apps.chat_v1.types import action_status +from google.apps.chat_v1.types import annotation +from google.apps.chat_v1.types import attachment +from google.apps.chat_v1.types import contextual_addon +from google.apps.chat_v1.types import deletion_metadata +from google.apps.chat_v1.types import group +from google.apps.chat_v1.types import history_state +from google.apps.chat_v1.types import matched_url +from google.apps.chat_v1.types import membership +from google.apps.chat_v1.types import membership as gc_membership +from google.apps.chat_v1.types import message +from google.apps.chat_v1.types import message as gc_message +from google.apps.chat_v1.types import reaction +from google.apps.chat_v1.types import reaction as gc_reaction +from google.apps.chat_v1.types import slash_command +from google.apps.chat_v1.types import space +from google.apps.chat_v1.types import space as gc_space +from google.apps.chat_v1.types import space_read_state +from google.apps.chat_v1.types import space_read_state as gc_space_read_state +from google.apps.chat_v1.types import space_setup +from google.apps.chat_v1.types import thread_read_state +from google.apps.chat_v1.types import user +from google.apps.chat_v1.types import widgets +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.rpc import code_pb2 # type: ignore +from google.type import color_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ChatServiceClient._get_default_mtls_endpoint(None) is None + assert ChatServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ChatServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ChatServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ChatServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ChatServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert ChatServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ChatServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ChatServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + ChatServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert ChatServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ChatServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ChatServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ChatServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert ChatServiceClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert ChatServiceClient._get_client_cert_source(None, False) is None + assert ChatServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ChatServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert ChatServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert ChatServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(ChatServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ChatServiceClient)) +@mock.patch.object(ChatServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ChatServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ChatServiceClient._DEFAULT_UNIVERSE + default_endpoint = ChatServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ChatServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert ChatServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert ChatServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ChatServiceClient.DEFAULT_MTLS_ENDPOINT + assert ChatServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert ChatServiceClient._get_api_endpoint(None, None, default_universe, "always") == ChatServiceClient.DEFAULT_MTLS_ENDPOINT + assert ChatServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ChatServiceClient.DEFAULT_MTLS_ENDPOINT + assert ChatServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert ChatServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + ChatServiceClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ChatServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert ChatServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert ChatServiceClient._get_universe_domain(None, None) == ChatServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + ChatServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ChatServiceClient, transports.ChatServiceGrpcTransport, "grpc"), + (ChatServiceClient, transports.ChatServiceRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ChatServiceClient, "grpc"), + (ChatServiceAsyncClient, "grpc_asyncio"), + (ChatServiceClient, "rest"), +]) +def test_chat_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'chat.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://chat.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ChatServiceGrpcTransport, "grpc"), + (transports.ChatServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ChatServiceRestTransport, "rest"), +]) +def test_chat_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ChatServiceClient, "grpc"), + (ChatServiceAsyncClient, "grpc_asyncio"), + (ChatServiceClient, "rest"), +]) +def test_chat_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'chat.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://chat.googleapis.com' + ) + + +def test_chat_service_client_get_transport_class(): + transport = ChatServiceClient.get_transport_class() + available_transports = [ + transports.ChatServiceGrpcTransport, + transports.ChatServiceRestTransport, + ] + assert transport in available_transports + + transport = ChatServiceClient.get_transport_class("grpc") + assert transport == transports.ChatServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ChatServiceClient, transports.ChatServiceGrpcTransport, "grpc"), + (ChatServiceAsyncClient, transports.ChatServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ChatServiceClient, transports.ChatServiceRestTransport, "rest"), +]) +@mock.patch.object(ChatServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ChatServiceClient)) +@mock.patch.object(ChatServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ChatServiceAsyncClient)) +def test_chat_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(ChatServiceClient, '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(ChatServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ChatServiceClient, transports.ChatServiceGrpcTransport, "grpc", "true"), + (ChatServiceAsyncClient, transports.ChatServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ChatServiceClient, transports.ChatServiceGrpcTransport, "grpc", "false"), + (ChatServiceAsyncClient, transports.ChatServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ChatServiceClient, transports.ChatServiceRestTransport, "rest", "true"), + (ChatServiceClient, transports.ChatServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(ChatServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ChatServiceClient)) +@mock.patch.object(ChatServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ChatServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_chat_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + ChatServiceClient, ChatServiceAsyncClient +]) +@mock.patch.object(ChatServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ChatServiceClient)) +@mock.patch.object(ChatServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ChatServiceAsyncClient)) +def test_chat_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + ChatServiceClient, ChatServiceAsyncClient +]) +@mock.patch.object(ChatServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ChatServiceClient)) +@mock.patch.object(ChatServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ChatServiceAsyncClient)) +def test_chat_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ChatServiceClient._DEFAULT_UNIVERSE + default_endpoint = ChatServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ChatServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ChatServiceClient, transports.ChatServiceGrpcTransport, "grpc"), + (ChatServiceAsyncClient, transports.ChatServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ChatServiceClient, transports.ChatServiceRestTransport, "rest"), +]) +def test_chat_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ChatServiceClient, transports.ChatServiceGrpcTransport, "grpc", grpc_helpers), + (ChatServiceAsyncClient, transports.ChatServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ChatServiceClient, transports.ChatServiceRestTransport, "rest", None), +]) +def test_chat_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_chat_service_client_client_options_from_dict(): + with mock.patch('google.apps.chat_v1.services.chat_service.transports.ChatServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ChatServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ChatServiceClient, transports.ChatServiceGrpcTransport, "grpc", grpc_helpers), + (ChatServiceAsyncClient, transports.ChatServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_chat_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "chat.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/chat.bot', + 'https://www.googleapis.com/auth/chat.delete', + 'https://www.googleapis.com/auth/chat.import', + 'https://www.googleapis.com/auth/chat.memberships', + 'https://www.googleapis.com/auth/chat.memberships.app', + 'https://www.googleapis.com/auth/chat.memberships.readonly', + 'https://www.googleapis.com/auth/chat.messages', + 'https://www.googleapis.com/auth/chat.messages.create', + 'https://www.googleapis.com/auth/chat.messages.reactions', + 'https://www.googleapis.com/auth/chat.messages.reactions.create', + 'https://www.googleapis.com/auth/chat.messages.reactions.readonly', + 'https://www.googleapis.com/auth/chat.messages.readonly', + 'https://www.googleapis.com/auth/chat.spaces', + 'https://www.googleapis.com/auth/chat.spaces.create', + 'https://www.googleapis.com/auth/chat.spaces.readonly', + 'https://www.googleapis.com/auth/chat.users.readstate', + 'https://www.googleapis.com/auth/chat.users.readstate.readonly', +), + scopes=None, + default_host="chat.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + gc_message.CreateMessageRequest, + dict, +]) +def test_create_message(request_type, transport: str = 'grpc'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_message), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gc_message.Message( + name='name_value', + text='text_value', + formatted_text='formatted_text_value', + fallback_text='fallback_text_value', + argument_text='argument_text_value', + thread_reply=True, + client_assigned_message_id='client_assigned_message_id_value', + ) + response = client.create_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gc_message.CreateMessageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_message.Message) + assert response.name == 'name_value' + assert response.text == 'text_value' + assert response.formatted_text == 'formatted_text_value' + assert response.fallback_text == 'fallback_text_value' + assert response.argument_text == 'argument_text_value' + assert response.thread_reply is True + assert response.client_assigned_message_id == 'client_assigned_message_id_value' + + +def test_create_message_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=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_message), + '__call__') as call: + client.create_message() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_message.CreateMessageRequest() + + +def test_create_message_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gc_message.CreateMessageRequest( + parent='parent_value', + thread_key='thread_key_value', + request_id='request_id_value', + message_id='message_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_message), + '__call__') as call: + client.create_message(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_message.CreateMessageRequest( + parent='parent_value', + thread_key='thread_key_value', + request_id='request_id_value', + message_id='message_id_value', + ) + +@pytest.mark.asyncio +async def test_create_message_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_message), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_message.Message( + name='name_value', + text='text_value', + formatted_text='formatted_text_value', + fallback_text='fallback_text_value', + argument_text='argument_text_value', + thread_reply=True, + client_assigned_message_id='client_assigned_message_id_value', + )) + response = await client.create_message() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_message.CreateMessageRequest() + +@pytest.mark.asyncio +async def test_create_message_async(transport: str = 'grpc_asyncio', request_type=gc_message.CreateMessageRequest): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_message), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gc_message.Message( + name='name_value', + text='text_value', + formatted_text='formatted_text_value', + fallback_text='fallback_text_value', + argument_text='argument_text_value', + thread_reply=True, + client_assigned_message_id='client_assigned_message_id_value', + )) + response = await client.create_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gc_message.CreateMessageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_message.Message) + assert response.name == 'name_value' + assert response.text == 'text_value' + assert response.formatted_text == 'formatted_text_value' + assert response.fallback_text == 'fallback_text_value' + assert response.argument_text == 'argument_text_value' + assert response.thread_reply is True + assert response.client_assigned_message_id == 'client_assigned_message_id_value' + + +@pytest.mark.asyncio +async def test_create_message_async_from_dict(): + await test_create_message_async(request_type=dict) + + +def test_create_message_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gc_message.CreateMessageRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_message), + '__call__') as call: + call.return_value = gc_message.Message() + client.create_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_message_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gc_message.CreateMessageRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_message), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_message.Message()) + await client.create_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_message_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_message), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gc_message.Message() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_message( + parent='parent_value', + message=gc_message.Message(name='name_value'), + message_id='message_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].message + mock_val = gc_message.Message(name='name_value') + assert arg == mock_val + arg = args[0].message_id + mock_val = 'message_id_value' + assert arg == mock_val + + +def test_create_message_flattened_error(): + client = ChatServiceClient( + credentials=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_message( + gc_message.CreateMessageRequest(), + parent='parent_value', + message=gc_message.Message(name='name_value'), + message_id='message_id_value', + ) + +@pytest.mark.asyncio +async def test_create_message_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_message), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gc_message.Message() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_message.Message()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_message( + parent='parent_value', + message=gc_message.Message(name='name_value'), + message_id='message_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].message + mock_val = gc_message.Message(name='name_value') + assert arg == mock_val + arg = args[0].message_id + mock_val = 'message_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_message_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_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_message( + gc_message.CreateMessageRequest(), + parent='parent_value', + message=gc_message.Message(name='name_value'), + message_id='message_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + message.ListMessagesRequest, + dict, +]) +def test_list_messages(request_type, transport: str = 'grpc'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = message.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] + request = message.ListMessagesRequest() + assert args[0] == request + + # 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=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] == message.ListMessagesRequest() + + +def test_list_messages_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = message.ListMessagesRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_messages), + '__call__') as call: + client.list_messages(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == message.ListMessagesRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +@pytest.mark.asyncio +async def test_list_messages_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_messages), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(message.ListMessagesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_messages() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == message.ListMessagesRequest() + +@pytest.mark.asyncio +async def test_list_messages_async(transport: str = 'grpc_asyncio', request_type=message.ListMessagesRequest): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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(message.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] + request = message.ListMessagesRequest() + assert args[0] == request + + # 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 = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = message.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 = message.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 = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = message.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(message.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 = ChatServiceClient( + 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 = message.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 = ChatServiceClient( + credentials=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( + message.ListMessagesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_messages_flattened_async(): + client = ChatServiceAsyncClient( + 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 = message.ListMessagesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(message.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 = ChatServiceAsyncClient( + credentials=ga_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( + message.ListMessagesRequest(), + parent='parent_value', + ) + + +def test_list_messages_pager(transport_name: str = "grpc"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_messages), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + message.ListMessagesResponse( + messages=[ + message.Message(), + message.Message(), + message.Message(), + ], + next_page_token='abc', + ), + message.ListMessagesResponse( + messages=[], + next_page_token='def', + ), + message.ListMessagesResponse( + messages=[ + message.Message(), + ], + next_page_token='ghi', + ), + message.ListMessagesResponse( + messages=[ + message.Message(), + message.Message(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_messages(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, message.Message) + for i in results) +def test_list_messages_pages(transport_name: str = "grpc"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_messages), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + message.ListMessagesResponse( + messages=[ + message.Message(), + message.Message(), + message.Message(), + ], + next_page_token='abc', + ), + message.ListMessagesResponse( + messages=[], + next_page_token='def', + ), + message.ListMessagesResponse( + messages=[ + message.Message(), + ], + next_page_token='ghi', + ), + message.ListMessagesResponse( + messages=[ + message.Message(), + message.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 = ChatServiceAsyncClient( + 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 = ( + message.ListMessagesResponse( + messages=[ + message.Message(), + message.Message(), + message.Message(), + ], + next_page_token='abc', + ), + message.ListMessagesResponse( + messages=[], + next_page_token='def', + ), + message.ListMessagesResponse( + messages=[ + message.Message(), + ], + next_page_token='ghi', + ), + message.ListMessagesResponse( + messages=[ + message.Message(), + message.Message(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_messages(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, message.Message) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_messages_async_pages(): + client = ChatServiceAsyncClient( + 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 = ( + message.ListMessagesResponse( + messages=[ + message.Message(), + message.Message(), + message.Message(), + ], + next_page_token='abc', + ), + message.ListMessagesResponse( + messages=[], + next_page_token='def', + ), + message.ListMessagesResponse( + messages=[ + message.Message(), + ], + next_page_token='ghi', + ), + message.ListMessagesResponse( + messages=[ + message.Message(), + message.Message(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_messages(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + membership.ListMembershipsRequest, + dict, +]) +def test_list_memberships(request_type, transport: str = 'grpc'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_memberships), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = membership.ListMembershipsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_memberships(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = membership.ListMembershipsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMembershipsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_memberships_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=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_memberships), + '__call__') as call: + client.list_memberships() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == membership.ListMembershipsRequest() + + +def test_list_memberships_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = membership.ListMembershipsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memberships), + '__call__') as call: + client.list_memberships(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == membership.ListMembershipsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + +@pytest.mark.asyncio +async def test_list_memberships_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memberships), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(membership.ListMembershipsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_memberships() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == membership.ListMembershipsRequest() + +@pytest.mark.asyncio +async def test_list_memberships_async(transport: str = 'grpc_asyncio', request_type=membership.ListMembershipsRequest): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_memberships), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(membership.ListMembershipsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_memberships(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = membership.ListMembershipsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMembershipsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_memberships_async_from_dict(): + await test_list_memberships_async(request_type=dict) + + +def test_list_memberships_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = membership.ListMembershipsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memberships), + '__call__') as call: + call.return_value = membership.ListMembershipsResponse() + client.list_memberships(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_memberships_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = membership.ListMembershipsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memberships), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(membership.ListMembershipsResponse()) + await client.list_memberships(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_memberships_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memberships), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = membership.ListMembershipsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_memberships( + 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_memberships_flattened_error(): + client = ChatServiceClient( + credentials=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_memberships( + membership.ListMembershipsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_memberships_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memberships), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = membership.ListMembershipsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(membership.ListMembershipsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_memberships( + 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_memberships_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_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_memberships( + membership.ListMembershipsRequest(), + parent='parent_value', + ) + + +def test_list_memberships_pager(transport_name: str = "grpc"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memberships), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), + ], + next_page_token='abc', + ), + membership.ListMembershipsResponse( + memberships=[], + next_page_token='def', + ), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + ], + next_page_token='ghi', + ), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_memberships(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, membership.Membership) + for i in results) +def test_list_memberships_pages(transport_name: str = "grpc"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memberships), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), + ], + next_page_token='abc', + ), + membership.ListMembershipsResponse( + memberships=[], + next_page_token='def', + ), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + ], + next_page_token='ghi', + ), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + ], + ), + RuntimeError, + ) + pages = list(client.list_memberships(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_memberships_async_pager(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memberships), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), + ], + next_page_token='abc', + ), + membership.ListMembershipsResponse( + memberships=[], + next_page_token='def', + ), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + ], + next_page_token='ghi', + ), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_memberships(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, membership.Membership) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_memberships_async_pages(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memberships), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), + ], + next_page_token='abc', + ), + membership.ListMembershipsResponse( + memberships=[], + next_page_token='def', + ), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + ], + next_page_token='ghi', + ), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_memberships(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + membership.GetMembershipRequest, + dict, +]) +def test_get_membership(request_type, transport: str = 'grpc'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = membership.Membership( + name='name_value', + state=membership.Membership.MembershipState.JOINED, + role=membership.Membership.MembershipRole.ROLE_MEMBER, + ) + response = client.get_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = membership.GetMembershipRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.Membership) + assert response.name == 'name_value' + assert response.state == membership.Membership.MembershipState.JOINED + assert response.role == membership.Membership.MembershipRole.ROLE_MEMBER + + +def test_get_membership_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=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_membership), + '__call__') as call: + client.get_membership() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == membership.GetMembershipRequest() + + +def test_get_membership_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = membership.GetMembershipRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership), + '__call__') as call: + client.get_membership(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == membership.GetMembershipRequest( + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_membership_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(membership.Membership( + name='name_value', + state=membership.Membership.MembershipState.JOINED, + role=membership.Membership.MembershipRole.ROLE_MEMBER, + )) + response = await client.get_membership() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == membership.GetMembershipRequest() + +@pytest.mark.asyncio +async def test_get_membership_async(transport: str = 'grpc_asyncio', request_type=membership.GetMembershipRequest): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(membership.Membership( + name='name_value', + state=membership.Membership.MembershipState.JOINED, + role=membership.Membership.MembershipRole.ROLE_MEMBER, + )) + response = await client.get_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = membership.GetMembershipRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.Membership) + assert response.name == 'name_value' + assert response.state == membership.Membership.MembershipState.JOINED + assert response.role == membership.Membership.MembershipRole.ROLE_MEMBER + + +@pytest.mark.asyncio +async def test_get_membership_async_from_dict(): + await test_get_membership_async(request_type=dict) + + +def test_get_membership_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = membership.GetMembershipRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership), + '__call__') as call: + call.return_value = membership.Membership() + client.get_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_membership_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = membership.GetMembershipRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(membership.Membership()) + await client.get_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_membership_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = membership.Membership() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_membership( + 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_membership_flattened_error(): + client = ChatServiceClient( + credentials=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_membership( + membership.GetMembershipRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_membership_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = membership.Membership() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(membership.Membership()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_membership( + 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_membership_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_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_membership( + membership.GetMembershipRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + message.GetMessageRequest, + dict, +]) +def test_get_message(request_type, transport: str = 'grpc'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_message), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = message.Message( + name='name_value', + text='text_value', + formatted_text='formatted_text_value', + fallback_text='fallback_text_value', + argument_text='argument_text_value', + thread_reply=True, + client_assigned_message_id='client_assigned_message_id_value', + ) + response = client.get_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = message.GetMessageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, message.Message) + assert response.name == 'name_value' + assert response.text == 'text_value' + assert response.formatted_text == 'formatted_text_value' + assert response.fallback_text == 'fallback_text_value' + assert response.argument_text == 'argument_text_value' + assert response.thread_reply is True + assert response.client_assigned_message_id == 'client_assigned_message_id_value' + + +def test_get_message_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=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_message), + '__call__') as call: + client.get_message() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == message.GetMessageRequest() + + +def test_get_message_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = message.GetMessageRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_message), + '__call__') as call: + client.get_message(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == message.GetMessageRequest( + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_message_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_message), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(message.Message( + name='name_value', + text='text_value', + formatted_text='formatted_text_value', + fallback_text='fallback_text_value', + argument_text='argument_text_value', + thread_reply=True, + client_assigned_message_id='client_assigned_message_id_value', + )) + response = await client.get_message() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == message.GetMessageRequest() + +@pytest.mark.asyncio +async def test_get_message_async(transport: str = 'grpc_asyncio', request_type=message.GetMessageRequest): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_message), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(message.Message( + name='name_value', + text='text_value', + formatted_text='formatted_text_value', + fallback_text='fallback_text_value', + argument_text='argument_text_value', + thread_reply=True, + client_assigned_message_id='client_assigned_message_id_value', + )) + response = await client.get_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = message.GetMessageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, message.Message) + assert response.name == 'name_value' + assert response.text == 'text_value' + assert response.formatted_text == 'formatted_text_value' + assert response.fallback_text == 'fallback_text_value' + assert response.argument_text == 'argument_text_value' + assert response.thread_reply is True + assert response.client_assigned_message_id == 'client_assigned_message_id_value' + + +@pytest.mark.asyncio +async def test_get_message_async_from_dict(): + await test_get_message_async(request_type=dict) + + +def test_get_message_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = message.GetMessageRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_message), + '__call__') as call: + call.return_value = message.Message() + client.get_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_message_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = message.GetMessageRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_message), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(message.Message()) + await client.get_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_message_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_message), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = message.Message() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_message( + 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_message_flattened_error(): + client = ChatServiceClient( + credentials=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_message( + message.GetMessageRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_message_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_message), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = message.Message() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(message.Message()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_message( + 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_message_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_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_message( + message.GetMessageRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gc_message.UpdateMessageRequest, + dict, +]) +def test_update_message(request_type, transport: str = 'grpc'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_message), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gc_message.Message( + name='name_value', + text='text_value', + formatted_text='formatted_text_value', + fallback_text='fallback_text_value', + argument_text='argument_text_value', + thread_reply=True, + client_assigned_message_id='client_assigned_message_id_value', + ) + response = client.update_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gc_message.UpdateMessageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_message.Message) + assert response.name == 'name_value' + assert response.text == 'text_value' + assert response.formatted_text == 'formatted_text_value' + assert response.fallback_text == 'fallback_text_value' + assert response.argument_text == 'argument_text_value' + assert response.thread_reply is True + assert response.client_assigned_message_id == 'client_assigned_message_id_value' + + +def test_update_message_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=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_message), + '__call__') as call: + client.update_message() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_message.UpdateMessageRequest() + + +def test_update_message_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gc_message.UpdateMessageRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_message), + '__call__') as call: + client.update_message(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_message.UpdateMessageRequest( + ) + +@pytest.mark.asyncio +async def test_update_message_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_message), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_message.Message( + name='name_value', + text='text_value', + formatted_text='formatted_text_value', + fallback_text='fallback_text_value', + argument_text='argument_text_value', + thread_reply=True, + client_assigned_message_id='client_assigned_message_id_value', + )) + response = await client.update_message() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_message.UpdateMessageRequest() + +@pytest.mark.asyncio +async def test_update_message_async(transport: str = 'grpc_asyncio', request_type=gc_message.UpdateMessageRequest): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_message), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gc_message.Message( + name='name_value', + text='text_value', + formatted_text='formatted_text_value', + fallback_text='fallback_text_value', + argument_text='argument_text_value', + thread_reply=True, + client_assigned_message_id='client_assigned_message_id_value', + )) + response = await client.update_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gc_message.UpdateMessageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_message.Message) + assert response.name == 'name_value' + assert response.text == 'text_value' + assert response.formatted_text == 'formatted_text_value' + assert response.fallback_text == 'fallback_text_value' + assert response.argument_text == 'argument_text_value' + assert response.thread_reply is True + assert response.client_assigned_message_id == 'client_assigned_message_id_value' + + +@pytest.mark.asyncio +async def test_update_message_async_from_dict(): + await test_update_message_async(request_type=dict) + + +def test_update_message_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gc_message.UpdateMessageRequest() + + request.message.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_message), + '__call__') as call: + call.return_value = gc_message.Message() + client.update_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'message.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_message_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gc_message.UpdateMessageRequest() + + request.message.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_message), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_message.Message()) + await client.update_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'message.name=name_value', + ) in kw['metadata'] + + +def test_update_message_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_message), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gc_message.Message() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_message( + message=gc_message.Message(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].message + mock_val = gc_message.Message(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_message_flattened_error(): + client = ChatServiceClient( + credentials=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_message( + gc_message.UpdateMessageRequest(), + message=gc_message.Message(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_message_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_message), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gc_message.Message() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_message.Message()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_message( + message=gc_message.Message(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].message + mock_val = gc_message.Message(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_message_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_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_message( + gc_message.UpdateMessageRequest(), + message=gc_message.Message(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + message.DeleteMessageRequest, + dict, +]) +def test_delete_message(request_type, transport: str = 'grpc'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_message), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = message.DeleteMessageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_message_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=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_message), + '__call__') as call: + client.delete_message() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == message.DeleteMessageRequest() + + +def test_delete_message_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = message.DeleteMessageRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_message), + '__call__') as call: + client.delete_message(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == message.DeleteMessageRequest( + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_message_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_message), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_message() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == message.DeleteMessageRequest() + +@pytest.mark.asyncio +async def test_delete_message_async(transport: str = 'grpc_asyncio', request_type=message.DeleteMessageRequest): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_message), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = message.DeleteMessageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_message_async_from_dict(): + await test_delete_message_async(request_type=dict) + + +def test_delete_message_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = message.DeleteMessageRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_message), + '__call__') as call: + call.return_value = None + client.delete_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_message_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = message.DeleteMessageRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_message), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_message_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_message), + '__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_message( + 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_message_flattened_error(): + client = ChatServiceClient( + credentials=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_message( + message.DeleteMessageRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_message_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_message), + '__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_message( + 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_message_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_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_message( + message.DeleteMessageRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + attachment.GetAttachmentRequest, + dict, +]) +def test_get_attachment(request_type, transport: str = 'grpc'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attachment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = attachment.Attachment( + name='name_value', + content_name='content_name_value', + content_type='content_type_value', + thumbnail_uri='thumbnail_uri_value', + download_uri='download_uri_value', + source=attachment.Attachment.Source.DRIVE_FILE, + ) + response = client.get_attachment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = attachment.GetAttachmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, attachment.Attachment) + assert response.name == 'name_value' + assert response.content_name == 'content_name_value' + assert response.content_type == 'content_type_value' + assert response.thumbnail_uri == 'thumbnail_uri_value' + assert response.download_uri == 'download_uri_value' + assert response.source == attachment.Attachment.Source.DRIVE_FILE + + +def test_get_attachment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=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_attachment), + '__call__') as call: + client.get_attachment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == attachment.GetAttachmentRequest() + + +def test_get_attachment_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = attachment.GetAttachmentRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attachment), + '__call__') as call: + client.get_attachment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == attachment.GetAttachmentRequest( + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_attachment_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attachment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attachment.Attachment( + name='name_value', + content_name='content_name_value', + content_type='content_type_value', + thumbnail_uri='thumbnail_uri_value', + download_uri='download_uri_value', + source=attachment.Attachment.Source.DRIVE_FILE, + )) + response = await client.get_attachment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == attachment.GetAttachmentRequest() + +@pytest.mark.asyncio +async def test_get_attachment_async(transport: str = 'grpc_asyncio', request_type=attachment.GetAttachmentRequest): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attachment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(attachment.Attachment( + name='name_value', + content_name='content_name_value', + content_type='content_type_value', + thumbnail_uri='thumbnail_uri_value', + download_uri='download_uri_value', + source=attachment.Attachment.Source.DRIVE_FILE, + )) + response = await client.get_attachment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = attachment.GetAttachmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, attachment.Attachment) + assert response.name == 'name_value' + assert response.content_name == 'content_name_value' + assert response.content_type == 'content_type_value' + assert response.thumbnail_uri == 'thumbnail_uri_value' + assert response.download_uri == 'download_uri_value' + assert response.source == attachment.Attachment.Source.DRIVE_FILE + + +@pytest.mark.asyncio +async def test_get_attachment_async_from_dict(): + await test_get_attachment_async(request_type=dict) + + +def test_get_attachment_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = attachment.GetAttachmentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attachment), + '__call__') as call: + call.return_value = attachment.Attachment() + client.get_attachment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_attachment_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = attachment.GetAttachmentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attachment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attachment.Attachment()) + await client.get_attachment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_attachment_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attachment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = attachment.Attachment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_attachment( + 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_attachment_flattened_error(): + client = ChatServiceClient( + credentials=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_attachment( + attachment.GetAttachmentRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_attachment_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attachment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = attachment.Attachment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attachment.Attachment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_attachment( + 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_attachment_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_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_attachment( + attachment.GetAttachmentRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + attachment.UploadAttachmentRequest, + dict, +]) +def test_upload_attachment(request_type, transport: str = 'grpc'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_attachment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = attachment.UploadAttachmentResponse( + ) + response = client.upload_attachment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = attachment.UploadAttachmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, attachment.UploadAttachmentResponse) + + +def test_upload_attachment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_attachment), + '__call__') as call: + client.upload_attachment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == attachment.UploadAttachmentRequest() + + +def test_upload_attachment_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = attachment.UploadAttachmentRequest( + parent='parent_value', + filename='filename_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_attachment), + '__call__') as call: + client.upload_attachment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == attachment.UploadAttachmentRequest( + parent='parent_value', + filename='filename_value', + ) + +@pytest.mark.asyncio +async def test_upload_attachment_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_attachment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attachment.UploadAttachmentResponse( + )) + response = await client.upload_attachment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == attachment.UploadAttachmentRequest() + +@pytest.mark.asyncio +async def test_upload_attachment_async(transport: str = 'grpc_asyncio', request_type=attachment.UploadAttachmentRequest): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_attachment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(attachment.UploadAttachmentResponse( + )) + response = await client.upload_attachment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = attachment.UploadAttachmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, attachment.UploadAttachmentResponse) + + +@pytest.mark.asyncio +async def test_upload_attachment_async_from_dict(): + await test_upload_attachment_async(request_type=dict) + + +def test_upload_attachment_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = attachment.UploadAttachmentRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_attachment), + '__call__') as call: + call.return_value = attachment.UploadAttachmentResponse() + client.upload_attachment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_upload_attachment_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = attachment.UploadAttachmentRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_attachment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(attachment.UploadAttachmentResponse()) + await client.upload_attachment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + space.ListSpacesRequest, + dict, +]) +def test_list_spaces(request_type, transport: str = 'grpc'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_spaces), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = space.ListSpacesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_spaces(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = space.ListSpacesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSpacesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_spaces_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=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_spaces), + '__call__') as call: + client.list_spaces() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space.ListSpacesRequest() + + +def test_list_spaces_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = space.ListSpacesRequest( + page_token='page_token_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_spaces), + '__call__') as call: + client.list_spaces(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space.ListSpacesRequest( + page_token='page_token_value', + filter='filter_value', + ) + +@pytest.mark.asyncio +async def test_list_spaces_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_spaces), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(space.ListSpacesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_spaces() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space.ListSpacesRequest() + +@pytest.mark.asyncio +async def test_list_spaces_async(transport: str = 'grpc_asyncio', request_type=space.ListSpacesRequest): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_spaces), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(space.ListSpacesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_spaces(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = space.ListSpacesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSpacesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_spaces_async_from_dict(): + await test_list_spaces_async(request_type=dict) + + +def test_list_spaces_pager(transport_name: str = "grpc"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_spaces), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + space.ListSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + space.Space(), + ], + next_page_token='abc', + ), + space.ListSpacesResponse( + spaces=[], + next_page_token='def', + ), + space.ListSpacesResponse( + spaces=[ + space.Space(), + ], + next_page_token='ghi', + ), + space.ListSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + ], + ), + RuntimeError, + ) + + metadata = () + pager = client.list_spaces(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, space.Space) + for i in results) +def test_list_spaces_pages(transport_name: str = "grpc"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_spaces), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + space.ListSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + space.Space(), + ], + next_page_token='abc', + ), + space.ListSpacesResponse( + spaces=[], + next_page_token='def', + ), + space.ListSpacesResponse( + spaces=[ + space.Space(), + ], + next_page_token='ghi', + ), + space.ListSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + ], + ), + RuntimeError, + ) + pages = list(client.list_spaces(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_spaces_async_pager(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_spaces), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + space.ListSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + space.Space(), + ], + next_page_token='abc', + ), + space.ListSpacesResponse( + spaces=[], + next_page_token='def', + ), + space.ListSpacesResponse( + spaces=[ + space.Space(), + ], + next_page_token='ghi', + ), + space.ListSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_spaces(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, space.Space) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_spaces_async_pages(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_spaces), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + space.ListSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + space.Space(), + ], + next_page_token='abc', + ), + space.ListSpacesResponse( + spaces=[], + next_page_token='def', + ), + space.ListSpacesResponse( + spaces=[ + space.Space(), + ], + next_page_token='ghi', + ), + space.ListSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_spaces(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + space.GetSpaceRequest, + dict, +]) +def test_get_space(request_type, transport: str = 'grpc'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_space), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = space.Space( + name='name_value', + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name='display_name_value', + external_user_allowed=True, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + ) + response = client.get_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = space.GetSpaceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, space.Space) + assert response.name == 'name_value' + assert response.type_ == space.Space.Type.ROOM + assert response.space_type == space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == 'display_name_value' + assert response.external_user_allowed is True + assert response.space_threading_state == space.Space.SpaceThreadingState.THREADED_MESSAGES + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +def test_get_space_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=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_space), + '__call__') as call: + client.get_space() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space.GetSpaceRequest() + + +def test_get_space_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = space.GetSpaceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_space), + '__call__') as call: + client.get_space(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space.GetSpaceRequest( + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_space_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_space), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(space.Space( + name='name_value', + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name='display_name_value', + external_user_allowed=True, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + )) + response = await client.get_space() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space.GetSpaceRequest() + +@pytest.mark.asyncio +async def test_get_space_async(transport: str = 'grpc_asyncio', request_type=space.GetSpaceRequest): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_space), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(space.Space( + name='name_value', + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name='display_name_value', + external_user_allowed=True, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + )) + response = await client.get_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = space.GetSpaceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, space.Space) + assert response.name == 'name_value' + assert response.type_ == space.Space.Type.ROOM + assert response.space_type == space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == 'display_name_value' + assert response.external_user_allowed is True + assert response.space_threading_state == space.Space.SpaceThreadingState.THREADED_MESSAGES + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +@pytest.mark.asyncio +async def test_get_space_async_from_dict(): + await test_get_space_async(request_type=dict) + + +def test_get_space_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = space.GetSpaceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_space), + '__call__') as call: + call.return_value = space.Space() + client.get_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_space_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = space.GetSpaceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_space), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(space.Space()) + await client.get_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_space_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_space), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = space.Space() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_space( + 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_space_flattened_error(): + client = ChatServiceClient( + credentials=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_space( + space.GetSpaceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_space_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_space), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = space.Space() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(space.Space()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_space( + 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_space_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_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_space( + space.GetSpaceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gc_space.CreateSpaceRequest, + dict, +]) +def test_create_space(request_type, transport: str = 'grpc'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_space), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gc_space.Space( + name='name_value', + type_=gc_space.Space.Type.ROOM, + space_type=gc_space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name='display_name_value', + external_user_allowed=True, + space_threading_state=gc_space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + ) + response = client.create_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gc_space.CreateSpaceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_space.Space) + assert response.name == 'name_value' + assert response.type_ == gc_space.Space.Type.ROOM + assert response.space_type == gc_space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == 'display_name_value' + assert response.external_user_allowed is True + assert response.space_threading_state == gc_space.Space.SpaceThreadingState.THREADED_MESSAGES + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +def test_create_space_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=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_space), + '__call__') as call: + client.create_space() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_space.CreateSpaceRequest() + + +def test_create_space_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gc_space.CreateSpaceRequest( + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_space), + '__call__') as call: + client.create_space(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_space.CreateSpaceRequest( + request_id='request_id_value', + ) + +@pytest.mark.asyncio +async def test_create_space_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_space), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_space.Space( + name='name_value', + type_=gc_space.Space.Type.ROOM, + space_type=gc_space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name='display_name_value', + external_user_allowed=True, + space_threading_state=gc_space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + )) + response = await client.create_space() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_space.CreateSpaceRequest() + +@pytest.mark.asyncio +async def test_create_space_async(transport: str = 'grpc_asyncio', request_type=gc_space.CreateSpaceRequest): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_space), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gc_space.Space( + name='name_value', + type_=gc_space.Space.Type.ROOM, + space_type=gc_space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name='display_name_value', + external_user_allowed=True, + space_threading_state=gc_space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + )) + response = await client.create_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gc_space.CreateSpaceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_space.Space) + assert response.name == 'name_value' + assert response.type_ == gc_space.Space.Type.ROOM + assert response.space_type == gc_space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == 'display_name_value' + assert response.external_user_allowed is True + assert response.space_threading_state == gc_space.Space.SpaceThreadingState.THREADED_MESSAGES + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +@pytest.mark.asyncio +async def test_create_space_async_from_dict(): + await test_create_space_async(request_type=dict) + + +def test_create_space_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_space), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gc_space.Space() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_space( + space=gc_space.Space(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].space + mock_val = gc_space.Space(name='name_value') + assert arg == mock_val + + +def test_create_space_flattened_error(): + client = ChatServiceClient( + credentials=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_space( + gc_space.CreateSpaceRequest(), + space=gc_space.Space(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_space_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_space), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gc_space.Space() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_space.Space()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_space( + space=gc_space.Space(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].space + mock_val = gc_space.Space(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_space_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_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_space( + gc_space.CreateSpaceRequest(), + space=gc_space.Space(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + space_setup.SetUpSpaceRequest, + dict, +]) +def test_set_up_space(request_type, transport: str = 'grpc'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_up_space), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = space.Space( + name='name_value', + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name='display_name_value', + external_user_allowed=True, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + ) + response = client.set_up_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = space_setup.SetUpSpaceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, space.Space) + assert response.name == 'name_value' + assert response.type_ == space.Space.Type.ROOM + assert response.space_type == space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == 'display_name_value' + assert response.external_user_allowed is True + assert response.space_threading_state == space.Space.SpaceThreadingState.THREADED_MESSAGES + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +def test_set_up_space_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=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_up_space), + '__call__') as call: + client.set_up_space() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space_setup.SetUpSpaceRequest() + + +def test_set_up_space_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = space_setup.SetUpSpaceRequest( + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_up_space), + '__call__') as call: + client.set_up_space(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space_setup.SetUpSpaceRequest( + request_id='request_id_value', + ) + +@pytest.mark.asyncio +async def test_set_up_space_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_up_space), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(space.Space( + name='name_value', + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name='display_name_value', + external_user_allowed=True, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + )) + response = await client.set_up_space() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space_setup.SetUpSpaceRequest() + +@pytest.mark.asyncio +async def test_set_up_space_async(transport: str = 'grpc_asyncio', request_type=space_setup.SetUpSpaceRequest): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_up_space), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(space.Space( + name='name_value', + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name='display_name_value', + external_user_allowed=True, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + )) + response = await client.set_up_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = space_setup.SetUpSpaceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, space.Space) + assert response.name == 'name_value' + assert response.type_ == space.Space.Type.ROOM + assert response.space_type == space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == 'display_name_value' + assert response.external_user_allowed is True + assert response.space_threading_state == space.Space.SpaceThreadingState.THREADED_MESSAGES + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +@pytest.mark.asyncio +async def test_set_up_space_async_from_dict(): + await test_set_up_space_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + gc_space.UpdateSpaceRequest, + dict, +]) +def test_update_space(request_type, transport: str = 'grpc'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_space), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gc_space.Space( + name='name_value', + type_=gc_space.Space.Type.ROOM, + space_type=gc_space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name='display_name_value', + external_user_allowed=True, + space_threading_state=gc_space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + ) + response = client.update_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gc_space.UpdateSpaceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_space.Space) + assert response.name == 'name_value' + assert response.type_ == gc_space.Space.Type.ROOM + assert response.space_type == gc_space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == 'display_name_value' + assert response.external_user_allowed is True + assert response.space_threading_state == gc_space.Space.SpaceThreadingState.THREADED_MESSAGES + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +def test_update_space_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=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_space), + '__call__') as call: + client.update_space() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_space.UpdateSpaceRequest() + + +def test_update_space_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gc_space.UpdateSpaceRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_space), + '__call__') as call: + client.update_space(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_space.UpdateSpaceRequest( + ) + +@pytest.mark.asyncio +async def test_update_space_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_space), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_space.Space( + name='name_value', + type_=gc_space.Space.Type.ROOM, + space_type=gc_space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name='display_name_value', + external_user_allowed=True, + space_threading_state=gc_space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + )) + response = await client.update_space() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_space.UpdateSpaceRequest() + +@pytest.mark.asyncio +async def test_update_space_async(transport: str = 'grpc_asyncio', request_type=gc_space.UpdateSpaceRequest): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_space), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gc_space.Space( + name='name_value', + type_=gc_space.Space.Type.ROOM, + space_type=gc_space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name='display_name_value', + external_user_allowed=True, + space_threading_state=gc_space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + )) + response = await client.update_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gc_space.UpdateSpaceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_space.Space) + assert response.name == 'name_value' + assert response.type_ == gc_space.Space.Type.ROOM + assert response.space_type == gc_space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == 'display_name_value' + assert response.external_user_allowed is True + assert response.space_threading_state == gc_space.Space.SpaceThreadingState.THREADED_MESSAGES + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +@pytest.mark.asyncio +async def test_update_space_async_from_dict(): + await test_update_space_async(request_type=dict) + + +def test_update_space_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gc_space.UpdateSpaceRequest() + + request.space.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_space), + '__call__') as call: + call.return_value = gc_space.Space() + client.update_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'space.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_space_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gc_space.UpdateSpaceRequest() + + request.space.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_space), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_space.Space()) + await client.update_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'space.name=name_value', + ) in kw['metadata'] + + +def test_update_space_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_space), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gc_space.Space() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_space( + space=gc_space.Space(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].space + mock_val = gc_space.Space(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_space_flattened_error(): + client = ChatServiceClient( + credentials=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_space( + gc_space.UpdateSpaceRequest(), + space=gc_space.Space(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_space_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_space), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gc_space.Space() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_space.Space()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_space( + space=gc_space.Space(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].space + mock_val = gc_space.Space(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_space_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_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_space( + gc_space.UpdateSpaceRequest(), + space=gc_space.Space(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + space.DeleteSpaceRequest, + dict, +]) +def test_delete_space(request_type, transport: str = 'grpc'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_space), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = space.DeleteSpaceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_space_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=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_space), + '__call__') as call: + client.delete_space() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space.DeleteSpaceRequest() + + +def test_delete_space_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = space.DeleteSpaceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_space), + '__call__') as call: + client.delete_space(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space.DeleteSpaceRequest( + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_space_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_space), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_space() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space.DeleteSpaceRequest() + +@pytest.mark.asyncio +async def test_delete_space_async(transport: str = 'grpc_asyncio', request_type=space.DeleteSpaceRequest): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_space), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = space.DeleteSpaceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_space_async_from_dict(): + await test_delete_space_async(request_type=dict) + + +def test_delete_space_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = space.DeleteSpaceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_space), + '__call__') as call: + call.return_value = None + client.delete_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_space_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = space.DeleteSpaceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_space), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_space_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_space), + '__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_space( + 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_space_flattened_error(): + client = ChatServiceClient( + credentials=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_space( + space.DeleteSpaceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_space_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_space), + '__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_space( + 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_space_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_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_space( + space.DeleteSpaceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + space.CompleteImportSpaceRequest, + dict, +]) +def test_complete_import_space(request_type, transport: str = 'grpc'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_import_space), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = space.CompleteImportSpaceResponse( + ) + response = client.complete_import_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = space.CompleteImportSpaceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, space.CompleteImportSpaceResponse) + + +def test_complete_import_space_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=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_import_space), + '__call__') as call: + client.complete_import_space() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space.CompleteImportSpaceRequest() + + +def test_complete_import_space_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = space.CompleteImportSpaceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_import_space), + '__call__') as call: + client.complete_import_space(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space.CompleteImportSpaceRequest( + name='name_value', + ) + +@pytest.mark.asyncio +async def test_complete_import_space_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_import_space), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(space.CompleteImportSpaceResponse( + )) + response = await client.complete_import_space() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space.CompleteImportSpaceRequest() + +@pytest.mark.asyncio +async def test_complete_import_space_async(transport: str = 'grpc_asyncio', request_type=space.CompleteImportSpaceRequest): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_import_space), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(space.CompleteImportSpaceResponse( + )) + response = await client.complete_import_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = space.CompleteImportSpaceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, space.CompleteImportSpaceResponse) + + +@pytest.mark.asyncio +async def test_complete_import_space_async_from_dict(): + await test_complete_import_space_async(request_type=dict) + + +def test_complete_import_space_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = space.CompleteImportSpaceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_import_space), + '__call__') as call: + call.return_value = space.CompleteImportSpaceResponse() + client.complete_import_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_import_space_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = space.CompleteImportSpaceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_import_space), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(space.CompleteImportSpaceResponse()) + await client.complete_import_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + space.FindDirectMessageRequest, + dict, +]) +def test_find_direct_message(request_type, transport: str = 'grpc'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.find_direct_message), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = space.Space( + name='name_value', + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name='display_name_value', + external_user_allowed=True, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + ) + response = client.find_direct_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = space.FindDirectMessageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, space.Space) + assert response.name == 'name_value' + assert response.type_ == space.Space.Type.ROOM + assert response.space_type == space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == 'display_name_value' + assert response.external_user_allowed is True + assert response.space_threading_state == space.Space.SpaceThreadingState.THREADED_MESSAGES + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +def test_find_direct_message_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.find_direct_message), + '__call__') as call: + client.find_direct_message() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space.FindDirectMessageRequest() + + +def test_find_direct_message_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = space.FindDirectMessageRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.find_direct_message), + '__call__') as call: + client.find_direct_message(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space.FindDirectMessageRequest( + name='name_value', + ) + +@pytest.mark.asyncio +async def test_find_direct_message_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.find_direct_message), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(space.Space( + name='name_value', + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name='display_name_value', + external_user_allowed=True, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + )) + response = await client.find_direct_message() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space.FindDirectMessageRequest() + +@pytest.mark.asyncio +async def test_find_direct_message_async(transport: str = 'grpc_asyncio', request_type=space.FindDirectMessageRequest): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.find_direct_message), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(space.Space( + name='name_value', + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name='display_name_value', + external_user_allowed=True, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + )) + response = await client.find_direct_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = space.FindDirectMessageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, space.Space) + assert response.name == 'name_value' + assert response.type_ == space.Space.Type.ROOM + assert response.space_type == space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == 'display_name_value' + assert response.external_user_allowed is True + assert response.space_threading_state == space.Space.SpaceThreadingState.THREADED_MESSAGES + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +@pytest.mark.asyncio +async def test_find_direct_message_async_from_dict(): + await test_find_direct_message_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + gc_membership.CreateMembershipRequest, + dict, +]) +def test_create_membership(request_type, transport: str = 'grpc'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gc_membership.Membership( + name='name_value', + state=gc_membership.Membership.MembershipState.JOINED, + role=gc_membership.Membership.MembershipRole.ROLE_MEMBER, + ) + response = client.create_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gc_membership.CreateMembershipRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_membership.Membership) + assert response.name == 'name_value' + assert response.state == gc_membership.Membership.MembershipState.JOINED + assert response.role == gc_membership.Membership.MembershipRole.ROLE_MEMBER + + +def test_create_membership_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=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_membership), + '__call__') as call: + client.create_membership() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_membership.CreateMembershipRequest() + + +def test_create_membership_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gc_membership.CreateMembershipRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership), + '__call__') as call: + client.create_membership(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_membership.CreateMembershipRequest( + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_create_membership_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_membership.Membership( + name='name_value', + state=gc_membership.Membership.MembershipState.JOINED, + role=gc_membership.Membership.MembershipRole.ROLE_MEMBER, + )) + response = await client.create_membership() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_membership.CreateMembershipRequest() + +@pytest.mark.asyncio +async def test_create_membership_async(transport: str = 'grpc_asyncio', request_type=gc_membership.CreateMembershipRequest): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gc_membership.Membership( + name='name_value', + state=gc_membership.Membership.MembershipState.JOINED, + role=gc_membership.Membership.MembershipRole.ROLE_MEMBER, + )) + response = await client.create_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gc_membership.CreateMembershipRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_membership.Membership) + assert response.name == 'name_value' + assert response.state == gc_membership.Membership.MembershipState.JOINED + assert response.role == gc_membership.Membership.MembershipRole.ROLE_MEMBER + + +@pytest.mark.asyncio +async def test_create_membership_async_from_dict(): + await test_create_membership_async(request_type=dict) + + +def test_create_membership_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gc_membership.CreateMembershipRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership), + '__call__') as call: + call.return_value = gc_membership.Membership() + client.create_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_membership_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gc_membership.CreateMembershipRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_membership.Membership()) + await client.create_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_membership_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gc_membership.Membership() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_membership( + parent='parent_value', + membership=gc_membership.Membership(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].membership + mock_val = gc_membership.Membership(name='name_value') + assert arg == mock_val + + +def test_create_membership_flattened_error(): + client = ChatServiceClient( + credentials=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_membership( + gc_membership.CreateMembershipRequest(), + parent='parent_value', + membership=gc_membership.Membership(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_membership_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gc_membership.Membership() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_membership.Membership()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_membership( + parent='parent_value', + membership=gc_membership.Membership(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].membership + mock_val = gc_membership.Membership(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_membership_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_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_membership( + gc_membership.CreateMembershipRequest(), + parent='parent_value', + membership=gc_membership.Membership(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + gc_membership.UpdateMembershipRequest, + dict, +]) +def test_update_membership(request_type, transport: str = 'grpc'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gc_membership.Membership( + name='name_value', + state=gc_membership.Membership.MembershipState.JOINED, + role=gc_membership.Membership.MembershipRole.ROLE_MEMBER, + ) + response = client.update_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gc_membership.UpdateMembershipRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_membership.Membership) + assert response.name == 'name_value' + assert response.state == gc_membership.Membership.MembershipState.JOINED + assert response.role == gc_membership.Membership.MembershipRole.ROLE_MEMBER + + +def test_update_membership_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=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_membership), + '__call__') as call: + client.update_membership() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_membership.UpdateMembershipRequest() + + +def test_update_membership_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gc_membership.UpdateMembershipRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership), + '__call__') as call: + client.update_membership(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_membership.UpdateMembershipRequest( + ) + +@pytest.mark.asyncio +async def test_update_membership_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_membership.Membership( + name='name_value', + state=gc_membership.Membership.MembershipState.JOINED, + role=gc_membership.Membership.MembershipRole.ROLE_MEMBER, + )) + response = await client.update_membership() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_membership.UpdateMembershipRequest() + +@pytest.mark.asyncio +async def test_update_membership_async(transport: str = 'grpc_asyncio', request_type=gc_membership.UpdateMembershipRequest): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gc_membership.Membership( + name='name_value', + state=gc_membership.Membership.MembershipState.JOINED, + role=gc_membership.Membership.MembershipRole.ROLE_MEMBER, + )) + response = await client.update_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gc_membership.UpdateMembershipRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_membership.Membership) + assert response.name == 'name_value' + assert response.state == gc_membership.Membership.MembershipState.JOINED + assert response.role == gc_membership.Membership.MembershipRole.ROLE_MEMBER + + +@pytest.mark.asyncio +async def test_update_membership_async_from_dict(): + await test_update_membership_async(request_type=dict) + + +def test_update_membership_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gc_membership.UpdateMembershipRequest() + + request.membership.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership), + '__call__') as call: + call.return_value = gc_membership.Membership() + client.update_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'membership.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_membership_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gc_membership.UpdateMembershipRequest() + + request.membership.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_membership.Membership()) + await client.update_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'membership.name=name_value', + ) in kw['metadata'] + + +def test_update_membership_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gc_membership.Membership() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_membership( + membership=gc_membership.Membership(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].membership + mock_val = gc_membership.Membership(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_membership_flattened_error(): + client = ChatServiceClient( + credentials=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_membership( + gc_membership.UpdateMembershipRequest(), + membership=gc_membership.Membership(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_membership_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gc_membership.Membership() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_membership.Membership()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_membership( + membership=gc_membership.Membership(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].membership + mock_val = gc_membership.Membership(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_membership_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_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_membership( + gc_membership.UpdateMembershipRequest(), + membership=gc_membership.Membership(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + membership.DeleteMembershipRequest, + dict, +]) +def test_delete_membership(request_type, transport: str = 'grpc'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = membership.Membership( + name='name_value', + state=membership.Membership.MembershipState.JOINED, + role=membership.Membership.MembershipRole.ROLE_MEMBER, + ) + response = client.delete_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = membership.DeleteMembershipRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.Membership) + assert response.name == 'name_value' + assert response.state == membership.Membership.MembershipState.JOINED + assert response.role == membership.Membership.MembershipRole.ROLE_MEMBER + + +def test_delete_membership_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=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_membership), + '__call__') as call: + client.delete_membership() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == membership.DeleteMembershipRequest() + + +def test_delete_membership_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = membership.DeleteMembershipRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership), + '__call__') as call: + client.delete_membership(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == membership.DeleteMembershipRequest( + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_membership_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(membership.Membership( + name='name_value', + state=membership.Membership.MembershipState.JOINED, + role=membership.Membership.MembershipRole.ROLE_MEMBER, + )) + response = await client.delete_membership() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == membership.DeleteMembershipRequest() + +@pytest.mark.asyncio +async def test_delete_membership_async(transport: str = 'grpc_asyncio', request_type=membership.DeleteMembershipRequest): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(membership.Membership( + name='name_value', + state=membership.Membership.MembershipState.JOINED, + role=membership.Membership.MembershipRole.ROLE_MEMBER, + )) + response = await client.delete_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = membership.DeleteMembershipRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.Membership) + assert response.name == 'name_value' + assert response.state == membership.Membership.MembershipState.JOINED + assert response.role == membership.Membership.MembershipRole.ROLE_MEMBER + + +@pytest.mark.asyncio +async def test_delete_membership_async_from_dict(): + await test_delete_membership_async(request_type=dict) + + +def test_delete_membership_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = membership.DeleteMembershipRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership), + '__call__') as call: + call.return_value = membership.Membership() + client.delete_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_membership_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = membership.DeleteMembershipRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(membership.Membership()) + await client.delete_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_membership_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = membership.Membership() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_membership( + 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_membership_flattened_error(): + client = ChatServiceClient( + credentials=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_membership( + membership.DeleteMembershipRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_membership_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = membership.Membership() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(membership.Membership()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_membership( + 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_membership_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_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_membership( + membership.DeleteMembershipRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gc_reaction.CreateReactionRequest, + dict, +]) +def test_create_reaction(request_type, transport: str = 'grpc'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_reaction), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gc_reaction.Reaction( + name='name_value', + ) + response = client.create_reaction(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gc_reaction.CreateReactionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_reaction.Reaction) + assert response.name == 'name_value' + + +def test_create_reaction_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=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_reaction), + '__call__') as call: + client.create_reaction() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_reaction.CreateReactionRequest() + + +def test_create_reaction_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gc_reaction.CreateReactionRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_reaction), + '__call__') as call: + client.create_reaction(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_reaction.CreateReactionRequest( + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_create_reaction_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_reaction), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_reaction.Reaction( + name='name_value', + )) + response = await client.create_reaction() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_reaction.CreateReactionRequest() + +@pytest.mark.asyncio +async def test_create_reaction_async(transport: str = 'grpc_asyncio', request_type=gc_reaction.CreateReactionRequest): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_reaction), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gc_reaction.Reaction( + name='name_value', + )) + response = await client.create_reaction(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gc_reaction.CreateReactionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_reaction.Reaction) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_create_reaction_async_from_dict(): + await test_create_reaction_async(request_type=dict) + + +def test_create_reaction_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gc_reaction.CreateReactionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_reaction), + '__call__') as call: + call.return_value = gc_reaction.Reaction() + client.create_reaction(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_reaction_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gc_reaction.CreateReactionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_reaction), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_reaction.Reaction()) + await client.create_reaction(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_reaction_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_reaction), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gc_reaction.Reaction() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_reaction( + parent='parent_value', + reaction=gc_reaction.Reaction(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].reaction + mock_val = gc_reaction.Reaction(name='name_value') + assert arg == mock_val + + +def test_create_reaction_flattened_error(): + client = ChatServiceClient( + credentials=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_reaction( + gc_reaction.CreateReactionRequest(), + parent='parent_value', + reaction=gc_reaction.Reaction(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_reaction_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_reaction), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gc_reaction.Reaction() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_reaction.Reaction()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_reaction( + parent='parent_value', + reaction=gc_reaction.Reaction(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].reaction + mock_val = gc_reaction.Reaction(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_reaction_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_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_reaction( + gc_reaction.CreateReactionRequest(), + parent='parent_value', + reaction=gc_reaction.Reaction(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + reaction.ListReactionsRequest, + dict, +]) +def test_list_reactions(request_type, transport: str = 'grpc'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_reactions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = reaction.ListReactionsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_reactions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = reaction.ListReactionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListReactionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_reactions_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=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_reactions), + '__call__') as call: + client.list_reactions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == reaction.ListReactionsRequest() + + +def test_list_reactions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = reaction.ListReactionsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_reactions), + '__call__') as call: + client.list_reactions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == reaction.ListReactionsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + +@pytest.mark.asyncio +async def test_list_reactions_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_reactions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(reaction.ListReactionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_reactions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == reaction.ListReactionsRequest() + +@pytest.mark.asyncio +async def test_list_reactions_async(transport: str = 'grpc_asyncio', request_type=reaction.ListReactionsRequest): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_reactions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(reaction.ListReactionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_reactions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = reaction.ListReactionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListReactionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_reactions_async_from_dict(): + await test_list_reactions_async(request_type=dict) + + +def test_list_reactions_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reaction.ListReactionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_reactions), + '__call__') as call: + call.return_value = reaction.ListReactionsResponse() + client.list_reactions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_reactions_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reaction.ListReactionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_reactions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(reaction.ListReactionsResponse()) + await client.list_reactions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_reactions_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_reactions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = reaction.ListReactionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_reactions( + 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_reactions_flattened_error(): + client = ChatServiceClient( + credentials=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_reactions( + reaction.ListReactionsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_reactions_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_reactions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = reaction.ListReactionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(reaction.ListReactionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_reactions( + 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_reactions_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_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_reactions( + reaction.ListReactionsRequest(), + parent='parent_value', + ) + + +def test_list_reactions_pager(transport_name: str = "grpc"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_reactions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + reaction.Reaction(), + reaction.Reaction(), + ], + next_page_token='abc', + ), + reaction.ListReactionsResponse( + reactions=[], + next_page_token='def', + ), + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + ], + next_page_token='ghi', + ), + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + reaction.Reaction(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_reactions(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, reaction.Reaction) + for i in results) +def test_list_reactions_pages(transport_name: str = "grpc"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_reactions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + reaction.Reaction(), + reaction.Reaction(), + ], + next_page_token='abc', + ), + reaction.ListReactionsResponse( + reactions=[], + next_page_token='def', + ), + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + ], + next_page_token='ghi', + ), + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + reaction.Reaction(), + ], + ), + RuntimeError, + ) + pages = list(client.list_reactions(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_reactions_async_pager(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_reactions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + reaction.Reaction(), + reaction.Reaction(), + ], + next_page_token='abc', + ), + reaction.ListReactionsResponse( + reactions=[], + next_page_token='def', + ), + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + ], + next_page_token='ghi', + ), + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + reaction.Reaction(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_reactions(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, reaction.Reaction) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_reactions_async_pages(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_reactions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + reaction.Reaction(), + reaction.Reaction(), + ], + next_page_token='abc', + ), + reaction.ListReactionsResponse( + reactions=[], + next_page_token='def', + ), + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + ], + next_page_token='ghi', + ), + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + reaction.Reaction(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_reactions(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + reaction.DeleteReactionRequest, + dict, +]) +def test_delete_reaction(request_type, transport: str = 'grpc'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_reaction), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_reaction(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = reaction.DeleteReactionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_reaction_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=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_reaction), + '__call__') as call: + client.delete_reaction() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == reaction.DeleteReactionRequest() + + +def test_delete_reaction_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = reaction.DeleteReactionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_reaction), + '__call__') as call: + client.delete_reaction(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == reaction.DeleteReactionRequest( + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_reaction_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_reaction), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_reaction() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == reaction.DeleteReactionRequest() + +@pytest.mark.asyncio +async def test_delete_reaction_async(transport: str = 'grpc_asyncio', request_type=reaction.DeleteReactionRequest): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_reaction), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_reaction(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = reaction.DeleteReactionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_reaction_async_from_dict(): + await test_delete_reaction_async(request_type=dict) + + +def test_delete_reaction_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reaction.DeleteReactionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_reaction), + '__call__') as call: + call.return_value = None + client.delete_reaction(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_reaction_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reaction.DeleteReactionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_reaction), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_reaction(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_reaction_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_reaction), + '__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_reaction( + 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_reaction_flattened_error(): + client = ChatServiceClient( + credentials=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_reaction( + reaction.DeleteReactionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_reaction_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_reaction), + '__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_reaction( + 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_reaction_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_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_reaction( + reaction.DeleteReactionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + space_read_state.GetSpaceReadStateRequest, + dict, +]) +def test_get_space_read_state(request_type, transport: str = 'grpc'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_space_read_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = space_read_state.SpaceReadState( + name='name_value', + ) + response = client.get_space_read_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = space_read_state.GetSpaceReadStateRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, space_read_state.SpaceReadState) + assert response.name == 'name_value' + + +def test_get_space_read_state_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=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_space_read_state), + '__call__') as call: + client.get_space_read_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space_read_state.GetSpaceReadStateRequest() + + +def test_get_space_read_state_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = space_read_state.GetSpaceReadStateRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_space_read_state), + '__call__') as call: + client.get_space_read_state(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space_read_state.GetSpaceReadStateRequest( + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_space_read_state_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_space_read_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(space_read_state.SpaceReadState( + name='name_value', + )) + response = await client.get_space_read_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space_read_state.GetSpaceReadStateRequest() + +@pytest.mark.asyncio +async def test_get_space_read_state_async(transport: str = 'grpc_asyncio', request_type=space_read_state.GetSpaceReadStateRequest): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_space_read_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(space_read_state.SpaceReadState( + name='name_value', + )) + response = await client.get_space_read_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = space_read_state.GetSpaceReadStateRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, space_read_state.SpaceReadState) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_space_read_state_async_from_dict(): + await test_get_space_read_state_async(request_type=dict) + + +def test_get_space_read_state_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = space_read_state.GetSpaceReadStateRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_space_read_state), + '__call__') as call: + call.return_value = space_read_state.SpaceReadState() + client.get_space_read_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_space_read_state_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = space_read_state.GetSpaceReadStateRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_space_read_state), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(space_read_state.SpaceReadState()) + await client.get_space_read_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_space_read_state_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_space_read_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = space_read_state.SpaceReadState() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_space_read_state( + 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_space_read_state_flattened_error(): + client = ChatServiceClient( + credentials=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_space_read_state( + space_read_state.GetSpaceReadStateRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_space_read_state_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_space_read_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = space_read_state.SpaceReadState() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(space_read_state.SpaceReadState()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_space_read_state( + 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_space_read_state_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_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_space_read_state( + space_read_state.GetSpaceReadStateRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gc_space_read_state.UpdateSpaceReadStateRequest, + dict, +]) +def test_update_space_read_state(request_type, transport: str = 'grpc'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_space_read_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gc_space_read_state.SpaceReadState( + name='name_value', + ) + response = client.update_space_read_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gc_space_read_state.UpdateSpaceReadStateRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_space_read_state.SpaceReadState) + assert response.name == 'name_value' + + +def test_update_space_read_state_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=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_space_read_state), + '__call__') as call: + client.update_space_read_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_space_read_state.UpdateSpaceReadStateRequest() + + +def test_update_space_read_state_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gc_space_read_state.UpdateSpaceReadStateRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_space_read_state), + '__call__') as call: + client.update_space_read_state(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_space_read_state.UpdateSpaceReadStateRequest( + ) + +@pytest.mark.asyncio +async def test_update_space_read_state_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_space_read_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_space_read_state.SpaceReadState( + name='name_value', + )) + response = await client.update_space_read_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_space_read_state.UpdateSpaceReadStateRequest() + +@pytest.mark.asyncio +async def test_update_space_read_state_async(transport: str = 'grpc_asyncio', request_type=gc_space_read_state.UpdateSpaceReadStateRequest): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_space_read_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gc_space_read_state.SpaceReadState( + name='name_value', + )) + response = await client.update_space_read_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gc_space_read_state.UpdateSpaceReadStateRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_space_read_state.SpaceReadState) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_update_space_read_state_async_from_dict(): + await test_update_space_read_state_async(request_type=dict) + + +def test_update_space_read_state_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gc_space_read_state.UpdateSpaceReadStateRequest() + + request.space_read_state.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_space_read_state), + '__call__') as call: + call.return_value = gc_space_read_state.SpaceReadState() + client.update_space_read_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'space_read_state.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_space_read_state_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gc_space_read_state.UpdateSpaceReadStateRequest() + + request.space_read_state.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_space_read_state), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_space_read_state.SpaceReadState()) + await client.update_space_read_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'space_read_state.name=name_value', + ) in kw['metadata'] + + +def test_update_space_read_state_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_space_read_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gc_space_read_state.SpaceReadState() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_space_read_state( + space_read_state=gc_space_read_state.SpaceReadState(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].space_read_state + mock_val = gc_space_read_state.SpaceReadState(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_space_read_state_flattened_error(): + client = ChatServiceClient( + credentials=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_space_read_state( + gc_space_read_state.UpdateSpaceReadStateRequest(), + space_read_state=gc_space_read_state.SpaceReadState(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_space_read_state_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_space_read_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gc_space_read_state.SpaceReadState() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_space_read_state.SpaceReadState()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_space_read_state( + space_read_state=gc_space_read_state.SpaceReadState(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].space_read_state + mock_val = gc_space_read_state.SpaceReadState(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_space_read_state_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_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_space_read_state( + gc_space_read_state.UpdateSpaceReadStateRequest(), + space_read_state=gc_space_read_state.SpaceReadState(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + thread_read_state.GetThreadReadStateRequest, + dict, +]) +def test_get_thread_read_state(request_type, transport: str = 'grpc'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_thread_read_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = thread_read_state.ThreadReadState( + name='name_value', + ) + response = client.get_thread_read_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = thread_read_state.GetThreadReadStateRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, thread_read_state.ThreadReadState) + assert response.name == 'name_value' + + +def test_get_thread_read_state_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=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_thread_read_state), + '__call__') as call: + client.get_thread_read_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == thread_read_state.GetThreadReadStateRequest() + + +def test_get_thread_read_state_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = thread_read_state.GetThreadReadStateRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_thread_read_state), + '__call__') as call: + client.get_thread_read_state(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == thread_read_state.GetThreadReadStateRequest( + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_thread_read_state_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_thread_read_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(thread_read_state.ThreadReadState( + name='name_value', + )) + response = await client.get_thread_read_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == thread_read_state.GetThreadReadStateRequest() + +@pytest.mark.asyncio +async def test_get_thread_read_state_async(transport: str = 'grpc_asyncio', request_type=thread_read_state.GetThreadReadStateRequest): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_thread_read_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(thread_read_state.ThreadReadState( + name='name_value', + )) + response = await client.get_thread_read_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = thread_read_state.GetThreadReadStateRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, thread_read_state.ThreadReadState) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_thread_read_state_async_from_dict(): + await test_get_thread_read_state_async(request_type=dict) + + +def test_get_thread_read_state_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = thread_read_state.GetThreadReadStateRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_thread_read_state), + '__call__') as call: + call.return_value = thread_read_state.ThreadReadState() + client.get_thread_read_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_thread_read_state_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = thread_read_state.GetThreadReadStateRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_thread_read_state), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(thread_read_state.ThreadReadState()) + await client.get_thread_read_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_thread_read_state_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_thread_read_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = thread_read_state.ThreadReadState() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_thread_read_state( + 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_thread_read_state_flattened_error(): + client = ChatServiceClient( + credentials=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_thread_read_state( + thread_read_state.GetThreadReadStateRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_thread_read_state_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_thread_read_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = thread_read_state.ThreadReadState() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(thread_read_state.ThreadReadState()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_thread_read_state( + 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_thread_read_state_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_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_thread_read_state( + thread_read_state.GetThreadReadStateRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gc_message.CreateMessageRequest, + dict, +]) +def test_create_message_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'spaces/sample1'} + request_init["message"] = {'name': 'name_value', 'sender': {'name': 'name_value', 'display_name': 'display_name_value', 'domain_id': 'domain_id_value', 'type_': 1, 'is_anonymous': True}, 'create_time': {'seconds': 751, 'nanos': 543}, 'last_update_time': {}, 'delete_time': {}, 'text': 'text_value', 'formatted_text': 'formatted_text_value', 'cards': [{'header': {'title': 'title_value', 'subtitle': 'subtitle_value', 'image_style': 1, 'image_url': 'image_url_value'}, 'sections': [{'header': 'header_value', 'widgets': [{'text_paragraph': {'text': 'text_value'}, 'image': {'image_url': 'image_url_value', 'on_click': {'action': {'action_method_name': 'action_method_name_value', 'parameters': [{'key': 'key_value', 'value': 'value_value'}]}, 'open_link': {'url': 'url_value'}}, 'aspect_ratio': 0.1278}, 'key_value': {'icon': 1, 'icon_url': 'icon_url_value', 'top_label': 'top_label_value', 'content': 'content_value', 'content_multiline': True, 'bottom_label': 'bottom_label_value', 'on_click': {}, 'button': {'text_button': {'text': 'text_value', 'on_click': {}}, 'image_button': {'icon': 1, 'icon_url': 'icon_url_value', 'on_click': {}, 'name': 'name_value'}}}, 'buttons': {}}]}], 'card_actions': [{'action_label': 'action_label_value', 'on_click': {}}], 'name': 'name_value'}], 'cards_v2': [{'card_id': 'card_id_value', 'card': {'header': {'title': 'title_value', 'subtitle': 'subtitle_value', 'image_type': 1, 'image_url': 'image_url_value', 'image_alt_text': 'image_alt_text_value'}, 'sections': [{'header': 'header_value', 'widgets': [{'text_paragraph': {'text': 'text_value'}, 'image': {'image_url': 'image_url_value', 'on_click': {'action': {'function': 'function_value', 'parameters': [{'key': 'key_value', 'value': 'value_value'}], 'load_indicator': 1, 'persist_values': True, 'interaction': 1}, 'open_link': {'url': 'url_value', 'open_as': 1, 'on_close': 1}, 'open_dynamic_link_action': {}, 'card': {}}, 'alt_text': 'alt_text_value'}, 'decorated_text': {'icon': {'known_icon': 'known_icon_value', 'icon_url': 'icon_url_value', 'material_icon': {'name': 'name_value', 'fill': True, 'weight': 648, 'grade': 515}, 'alt_text': 'alt_text_value', 'image_type': 1}, 'start_icon': {}, 'top_label': 'top_label_value', 'text': 'text_value', 'wrap_text': True, 'bottom_label': 'bottom_label_value', 'on_click': {}, 'button': {'text': 'text_value', 'icon': {}, 'color': {'red': 0.315, 'green': 0.529, 'blue': 0.424, 'alpha': {'value': 0.541}}, 'on_click': {}, 'disabled': True, 'alt_text': 'alt_text_value'}, 'switch_control': {'name': 'name_value', 'value': 'value_value', 'selected': True, 'on_change_action': {}, 'control_type': 1}, 'end_icon': {}}, 'button_list': {'buttons': {}}, 'text_input': {'name': 'name_value', 'label': 'label_value', 'hint_text': 'hint_text_value', 'value': 'value_value', 'type_': 1, 'on_change_action': {}, 'initial_suggestions': {'items': [{'text': 'text_value'}]}, 'auto_complete_action': {}, 'placeholder_text': 'placeholder_text_value'}, 'selection_input': {'name': 'name_value', 'label': 'label_value', 'type_': 1, 'items': [{'text': 'text_value', 'value': 'value_value', 'selected': True, 'start_icon_uri': 'start_icon_uri_value', 'bottom_text': 'bottom_text_value'}], 'on_change_action': {}, 'multi_select_max_selected_items': 3288, 'multi_select_min_query_length': 3107, 'external_data_source': {}, 'platform_data_source': {'common_data_source': 1}}, 'date_time_picker': {'name': 'name_value', 'label': 'label_value', 'type_': 1, 'value_ms_epoch': 1482, 'timezone_offset_date': 2126, 'on_change_action': {}}, 'divider': {}, 'grid': {'title': 'title_value', 'items': [{'id': 'id_value', 'image': {'image_uri': 'image_uri_value', 'alt_text': 'alt_text_value', 'crop_style': {'type_': 1, 'aspect_ratio': 0.1278}, 'border_style': {'type_': 1, 'stroke_color': {}, 'corner_radius': 1392}}, 'title': 'title_value', 'subtitle': 'subtitle_value', 'layout': 1}], 'border_style': {}, 'column_count': 1302, 'on_click': {}}, 'columns': {'column_items': [{'horizontal_size_style': 1, 'horizontal_alignment': 1, 'vertical_alignment': 1, 'widgets': [{'text_paragraph': {}, 'image': {}, 'decorated_text': {}, 'button_list': {}, 'text_input': {}, 'selection_input': {}, 'date_time_picker': {}}]}]}, 'horizontal_alignment': 1}], 'collapsible': True, 'uncollapsible_widgets_count': 2891}], 'section_divider_style': 1, 'card_actions': [{'action_label': 'action_label_value', 'on_click': {}}], 'name': 'name_value', 'fixed_footer': {'primary_button': {}, 'secondary_button': {}}, 'display_style': 1, 'peek_card_header': {}}}], 'annotations': [{'type_': 1, 'start_index': 1189, 'length': 642, 'user_mention': {'user': {}, 'type_': 1}, 'slash_command': {'bot': {}, 'type_': 1, 'command_name': 'command_name_value', 'command_id': 1035, 'triggers_dialog': True}, 'rich_link_metadata': {'uri': 'uri_value', 'rich_link_type': 1, 'drive_link_data': {'drive_data_ref': {'drive_file_id': 'drive_file_id_value'}, 'mime_type': 'mime_type_value'}}}], 'thread': {'name': 'name_value', 'thread_key': 'thread_key_value'}, 'space': {'name': 'name_value', 'type_': 1, 'space_type': 1, 'single_user_bot_dm': True, 'threaded': True, 'display_name': 'display_name_value', 'external_user_allowed': True, 'space_threading_state': 2, 'space_details': {'description': 'description_value', 'guidelines': 'guidelines_value'}, 'space_history_state': 1, 'import_mode': True, 'create_time': {}, 'admin_installed': True}, 'fallback_text': 'fallback_text_value', 'action_response': {'type_': 1, 'url': 'url_value', 'dialog_action': {'dialog': {'body': {}}, 'action_status': {'status_code': 1, 'user_facing_message': 'user_facing_message_value'}}, 'updated_widget': {'suggestions': {'items': {}}, 'widget': 'widget_value'}}, 'argument_text': 'argument_text_value', 'slash_command': {'command_id': 1035}, 'attachment': [{'name': 'name_value', 'content_name': 'content_name_value', 'content_type': 'content_type_value', 'attachment_data_ref': {'resource_name': 'resource_name_value', 'attachment_upload_token': 'attachment_upload_token_value'}, 'drive_data_ref': {}, 'thumbnail_uri': 'thumbnail_uri_value', 'download_uri': 'download_uri_value', 'source': 1}], 'matched_url': {'url': 'url_value'}, 'thread_reply': True, 'client_assigned_message_id': 'client_assigned_message_id_value', 'emoji_reaction_summaries': [{'emoji': {'unicode': 'unicode_value', 'custom_emoji': {'uid': 'uid_value'}}, 'reaction_count': 1501}], 'private_message_viewer': {}, 'deletion_metadata': {'deletion_type': 1}, 'quoted_message_metadata': {'name': 'name_value', 'last_update_time': {}}, 'attached_gifs': [{'uri': 'uri_value'}], 'accessory_widgets': [{'button_list': {}}]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gc_message.CreateMessageRequest.meta.fields["message"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["message"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["message"][field])): + del request_init["message"][field][i][subfield] + else: + del request_init["message"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gc_message.Message( + name='name_value', + text='text_value', + formatted_text='formatted_text_value', + fallback_text='fallback_text_value', + argument_text='argument_text_value', + thread_reply=True, + client_assigned_message_id='client_assigned_message_id_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gc_message.Message.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_message(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_message.Message) + assert response.name == 'name_value' + assert response.text == 'text_value' + assert response.formatted_text == 'formatted_text_value' + assert response.fallback_text == 'fallback_text_value' + assert response.argument_text == 'argument_text_value' + assert response.thread_reply is True + assert response.client_assigned_message_id == 'client_assigned_message_id_value' + + +def test_create_message_rest_required_fields(request_type=gc_message.CreateMessageRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_message._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_message._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("message_id", "message_reply_option", "request_id", "thread_key", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gc_message.Message() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gc_message.Message.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_message(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_message_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_message._get_unset_required_fields({}) + assert set(unset_fields) == (set(("messageId", "messageReplyOption", "requestId", "threadKey", )) & set(("parent", "message", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_message_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "post_create_message") as post, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "pre_create_message") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gc_message.CreateMessageRequest.pb(gc_message.CreateMessageRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gc_message.Message.to_json(gc_message.Message()) + + request = gc_message.CreateMessageRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gc_message.Message() + + client.create_message(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_message_rest_bad_request(transport: str = 'rest', request_type=gc_message.CreateMessageRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'spaces/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_message(request) + + +def test_create_message_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gc_message.Message() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'spaces/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + message=gc_message.Message(name='name_value'), + message_id='message_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gc_message.Message.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_message(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=spaces/*}/messages" % client.transport._host, args[1]) + + +def test_create_message_rest_flattened_error(transport: str = 'rest'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_message( + gc_message.CreateMessageRequest(), + parent='parent_value', + message=gc_message.Message(name='name_value'), + message_id='message_id_value', + ) + + +def test_create_message_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + message.ListMessagesRequest, + dict, +]) +def test_list_messages_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'spaces/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = message.ListMessagesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = message.ListMessagesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_messages(request) + + # 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_rest_required_fields(request_type=message.ListMessagesRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_messages._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_messages._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", "show_deleted", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = message.ListMessagesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = message.ListMessagesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_messages(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_messages_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_messages._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", "showDeleted", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_messages_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "post_list_messages") as post, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "pre_list_messages") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = message.ListMessagesRequest.pb(message.ListMessagesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = message.ListMessagesResponse.to_json(message.ListMessagesResponse()) + + request = message.ListMessagesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = message.ListMessagesResponse() + + client.list_messages(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_messages_rest_bad_request(transport: str = 'rest', request_type=message.ListMessagesRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'spaces/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_messages(request) + + +def test_list_messages_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = message.ListMessagesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'spaces/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = message.ListMessagesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_messages(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=spaces/*}/messages" % client.transport._host, args[1]) + + +def test_list_messages_rest_flattened_error(transport: str = 'rest'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_messages( + message.ListMessagesRequest(), + parent='parent_value', + ) + + +def test_list_messages_rest_pager(transport: str = 'rest'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + message.ListMessagesResponse( + messages=[ + message.Message(), + message.Message(), + message.Message(), + ], + next_page_token='abc', + ), + message.ListMessagesResponse( + messages=[], + next_page_token='def', + ), + message.ListMessagesResponse( + messages=[ + message.Message(), + ], + next_page_token='ghi', + ), + message.ListMessagesResponse( + messages=[ + message.Message(), + message.Message(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(message.ListMessagesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'spaces/sample1'} + + pager = client.list_messages(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, message.Message) + for i in results) + + pages = list(client.list_messages(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + membership.ListMembershipsRequest, + dict, +]) +def test_list_memberships_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'spaces/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = membership.ListMembershipsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = membership.ListMembershipsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_memberships(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMembershipsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_memberships_rest_required_fields(request_type=membership.ListMembershipsRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_memberships._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_memberships._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "page_size", "page_token", "show_groups", "show_invited", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = membership.ListMembershipsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = membership.ListMembershipsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_memberships(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_memberships_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_memberships._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", "showGroups", "showInvited", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_memberships_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "post_list_memberships") as post, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "pre_list_memberships") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = membership.ListMembershipsRequest.pb(membership.ListMembershipsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = membership.ListMembershipsResponse.to_json(membership.ListMembershipsResponse()) + + request = membership.ListMembershipsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = membership.ListMembershipsResponse() + + client.list_memberships(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_memberships_rest_bad_request(transport: str = 'rest', request_type=membership.ListMembershipsRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'spaces/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_memberships(request) + + +def test_list_memberships_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = membership.ListMembershipsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'spaces/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = membership.ListMembershipsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_memberships(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=spaces/*}/members" % client.transport._host, args[1]) + + +def test_list_memberships_rest_flattened_error(transport: str = 'rest'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_memberships( + membership.ListMembershipsRequest(), + parent='parent_value', + ) + + +def test_list_memberships_rest_pager(transport: str = 'rest'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), + ], + next_page_token='abc', + ), + membership.ListMembershipsResponse( + memberships=[], + next_page_token='def', + ), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + ], + next_page_token='ghi', + ), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(membership.ListMembershipsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'spaces/sample1'} + + pager = client.list_memberships(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, membership.Membership) + for i in results) + + pages = list(client.list_memberships(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + membership.GetMembershipRequest, + dict, +]) +def test_get_membership_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'spaces/sample1/members/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = membership.Membership( + name='name_value', + state=membership.Membership.MembershipState.JOINED, + role=membership.Membership.MembershipRole.ROLE_MEMBER, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = membership.Membership.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_membership(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.Membership) + assert response.name == 'name_value' + assert response.state == membership.Membership.MembershipState.JOINED + assert response.role == membership.Membership.MembershipRole.ROLE_MEMBER + + +def test_get_membership_rest_required_fields(request_type=membership.GetMembershipRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = membership.Membership() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = membership.Membership.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_membership(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_membership_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_membership._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_membership_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "post_get_membership") as post, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "pre_get_membership") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = membership.GetMembershipRequest.pb(membership.GetMembershipRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = membership.Membership.to_json(membership.Membership()) + + request = membership.GetMembershipRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = membership.Membership() + + client.get_membership(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_membership_rest_bad_request(transport: str = 'rest', request_type=membership.GetMembershipRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'spaces/sample1/members/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_membership(request) + + +def test_get_membership_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = membership.Membership() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'spaces/sample1/members/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = membership.Membership.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_membership(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=spaces/*/members/*}" % client.transport._host, args[1]) + + +def test_get_membership_rest_flattened_error(transport: str = 'rest'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_membership( + membership.GetMembershipRequest(), + name='name_value', + ) + + +def test_get_membership_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + message.GetMessageRequest, + dict, +]) +def test_get_message_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'spaces/sample1/messages/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = message.Message( + name='name_value', + text='text_value', + formatted_text='formatted_text_value', + fallback_text='fallback_text_value', + argument_text='argument_text_value', + thread_reply=True, + client_assigned_message_id='client_assigned_message_id_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = message.Message.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_message(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, message.Message) + assert response.name == 'name_value' + assert response.text == 'text_value' + assert response.formatted_text == 'formatted_text_value' + assert response.fallback_text == 'fallback_text_value' + assert response.argument_text == 'argument_text_value' + assert response.thread_reply is True + assert response.client_assigned_message_id == 'client_assigned_message_id_value' + + +def test_get_message_rest_required_fields(request_type=message.GetMessageRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_message._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_message._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = message.Message() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = message.Message.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_message(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_message_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_message._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_message_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "post_get_message") as post, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "pre_get_message") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = message.GetMessageRequest.pb(message.GetMessageRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = message.Message.to_json(message.Message()) + + request = message.GetMessageRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = message.Message() + + client.get_message(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_message_rest_bad_request(transport: str = 'rest', request_type=message.GetMessageRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'spaces/sample1/messages/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_message(request) + + +def test_get_message_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = message.Message() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'spaces/sample1/messages/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = message.Message.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_message(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=spaces/*/messages/*}" % client.transport._host, args[1]) + + +def test_get_message_rest_flattened_error(transport: str = 'rest'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_message( + message.GetMessageRequest(), + name='name_value', + ) + + +def test_get_message_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + gc_message.UpdateMessageRequest, + dict, +]) +def test_update_message_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'message': {'name': 'spaces/sample1/messages/sample2'}} + request_init["message"] = {'name': 'spaces/sample1/messages/sample2', 'sender': {'name': 'name_value', 'display_name': 'display_name_value', 'domain_id': 'domain_id_value', 'type_': 1, 'is_anonymous': True}, 'create_time': {'seconds': 751, 'nanos': 543}, 'last_update_time': {}, 'delete_time': {}, 'text': 'text_value', 'formatted_text': 'formatted_text_value', 'cards': [{'header': {'title': 'title_value', 'subtitle': 'subtitle_value', 'image_style': 1, 'image_url': 'image_url_value'}, 'sections': [{'header': 'header_value', 'widgets': [{'text_paragraph': {'text': 'text_value'}, 'image': {'image_url': 'image_url_value', 'on_click': {'action': {'action_method_name': 'action_method_name_value', 'parameters': [{'key': 'key_value', 'value': 'value_value'}]}, 'open_link': {'url': 'url_value'}}, 'aspect_ratio': 0.1278}, 'key_value': {'icon': 1, 'icon_url': 'icon_url_value', 'top_label': 'top_label_value', 'content': 'content_value', 'content_multiline': True, 'bottom_label': 'bottom_label_value', 'on_click': {}, 'button': {'text_button': {'text': 'text_value', 'on_click': {}}, 'image_button': {'icon': 1, 'icon_url': 'icon_url_value', 'on_click': {}, 'name': 'name_value'}}}, 'buttons': {}}]}], 'card_actions': [{'action_label': 'action_label_value', 'on_click': {}}], 'name': 'name_value'}], 'cards_v2': [{'card_id': 'card_id_value', 'card': {'header': {'title': 'title_value', 'subtitle': 'subtitle_value', 'image_type': 1, 'image_url': 'image_url_value', 'image_alt_text': 'image_alt_text_value'}, 'sections': [{'header': 'header_value', 'widgets': [{'text_paragraph': {'text': 'text_value'}, 'image': {'image_url': 'image_url_value', 'on_click': {'action': {'function': 'function_value', 'parameters': [{'key': 'key_value', 'value': 'value_value'}], 'load_indicator': 1, 'persist_values': True, 'interaction': 1}, 'open_link': {'url': 'url_value', 'open_as': 1, 'on_close': 1}, 'open_dynamic_link_action': {}, 'card': {}}, 'alt_text': 'alt_text_value'}, 'decorated_text': {'icon': {'known_icon': 'known_icon_value', 'icon_url': 'icon_url_value', 'material_icon': {'name': 'name_value', 'fill': True, 'weight': 648, 'grade': 515}, 'alt_text': 'alt_text_value', 'image_type': 1}, 'start_icon': {}, 'top_label': 'top_label_value', 'text': 'text_value', 'wrap_text': True, 'bottom_label': 'bottom_label_value', 'on_click': {}, 'button': {'text': 'text_value', 'icon': {}, 'color': {'red': 0.315, 'green': 0.529, 'blue': 0.424, 'alpha': {'value': 0.541}}, 'on_click': {}, 'disabled': True, 'alt_text': 'alt_text_value'}, 'switch_control': {'name': 'name_value', 'value': 'value_value', 'selected': True, 'on_change_action': {}, 'control_type': 1}, 'end_icon': {}}, 'button_list': {'buttons': {}}, 'text_input': {'name': 'name_value', 'label': 'label_value', 'hint_text': 'hint_text_value', 'value': 'value_value', 'type_': 1, 'on_change_action': {}, 'initial_suggestions': {'items': [{'text': 'text_value'}]}, 'auto_complete_action': {}, 'placeholder_text': 'placeholder_text_value'}, 'selection_input': {'name': 'name_value', 'label': 'label_value', 'type_': 1, 'items': [{'text': 'text_value', 'value': 'value_value', 'selected': True, 'start_icon_uri': 'start_icon_uri_value', 'bottom_text': 'bottom_text_value'}], 'on_change_action': {}, 'multi_select_max_selected_items': 3288, 'multi_select_min_query_length': 3107, 'external_data_source': {}, 'platform_data_source': {'common_data_source': 1}}, 'date_time_picker': {'name': 'name_value', 'label': 'label_value', 'type_': 1, 'value_ms_epoch': 1482, 'timezone_offset_date': 2126, 'on_change_action': {}}, 'divider': {}, 'grid': {'title': 'title_value', 'items': [{'id': 'id_value', 'image': {'image_uri': 'image_uri_value', 'alt_text': 'alt_text_value', 'crop_style': {'type_': 1, 'aspect_ratio': 0.1278}, 'border_style': {'type_': 1, 'stroke_color': {}, 'corner_radius': 1392}}, 'title': 'title_value', 'subtitle': 'subtitle_value', 'layout': 1}], 'border_style': {}, 'column_count': 1302, 'on_click': {}}, 'columns': {'column_items': [{'horizontal_size_style': 1, 'horizontal_alignment': 1, 'vertical_alignment': 1, 'widgets': [{'text_paragraph': {}, 'image': {}, 'decorated_text': {}, 'button_list': {}, 'text_input': {}, 'selection_input': {}, 'date_time_picker': {}}]}]}, 'horizontal_alignment': 1}], 'collapsible': True, 'uncollapsible_widgets_count': 2891}], 'section_divider_style': 1, 'card_actions': [{'action_label': 'action_label_value', 'on_click': {}}], 'name': 'name_value', 'fixed_footer': {'primary_button': {}, 'secondary_button': {}}, 'display_style': 1, 'peek_card_header': {}}}], 'annotations': [{'type_': 1, 'start_index': 1189, 'length': 642, 'user_mention': {'user': {}, 'type_': 1}, 'slash_command': {'bot': {}, 'type_': 1, 'command_name': 'command_name_value', 'command_id': 1035, 'triggers_dialog': True}, 'rich_link_metadata': {'uri': 'uri_value', 'rich_link_type': 1, 'drive_link_data': {'drive_data_ref': {'drive_file_id': 'drive_file_id_value'}, 'mime_type': 'mime_type_value'}}}], 'thread': {'name': 'name_value', 'thread_key': 'thread_key_value'}, 'space': {'name': 'name_value', 'type_': 1, 'space_type': 1, 'single_user_bot_dm': True, 'threaded': True, 'display_name': 'display_name_value', 'external_user_allowed': True, 'space_threading_state': 2, 'space_details': {'description': 'description_value', 'guidelines': 'guidelines_value'}, 'space_history_state': 1, 'import_mode': True, 'create_time': {}, 'admin_installed': True}, 'fallback_text': 'fallback_text_value', 'action_response': {'type_': 1, 'url': 'url_value', 'dialog_action': {'dialog': {'body': {}}, 'action_status': {'status_code': 1, 'user_facing_message': 'user_facing_message_value'}}, 'updated_widget': {'suggestions': {'items': {}}, 'widget': 'widget_value'}}, 'argument_text': 'argument_text_value', 'slash_command': {'command_id': 1035}, 'attachment': [{'name': 'name_value', 'content_name': 'content_name_value', 'content_type': 'content_type_value', 'attachment_data_ref': {'resource_name': 'resource_name_value', 'attachment_upload_token': 'attachment_upload_token_value'}, 'drive_data_ref': {}, 'thumbnail_uri': 'thumbnail_uri_value', 'download_uri': 'download_uri_value', 'source': 1}], 'matched_url': {'url': 'url_value'}, 'thread_reply': True, 'client_assigned_message_id': 'client_assigned_message_id_value', 'emoji_reaction_summaries': [{'emoji': {'unicode': 'unicode_value', 'custom_emoji': {'uid': 'uid_value'}}, 'reaction_count': 1501}], 'private_message_viewer': {}, 'deletion_metadata': {'deletion_type': 1}, 'quoted_message_metadata': {'name': 'name_value', 'last_update_time': {}}, 'attached_gifs': [{'uri': 'uri_value'}], 'accessory_widgets': [{'button_list': {}}]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gc_message.UpdateMessageRequest.meta.fields["message"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["message"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["message"][field])): + del request_init["message"][field][i][subfield] + else: + del request_init["message"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gc_message.Message( + name='name_value', + text='text_value', + formatted_text='formatted_text_value', + fallback_text='fallback_text_value', + argument_text='argument_text_value', + thread_reply=True, + client_assigned_message_id='client_assigned_message_id_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gc_message.Message.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_message(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_message.Message) + assert response.name == 'name_value' + assert response.text == 'text_value' + assert response.formatted_text == 'formatted_text_value' + assert response.fallback_text == 'fallback_text_value' + assert response.argument_text == 'argument_text_value' + assert response.thread_reply is True + assert response.client_assigned_message_id == 'client_assigned_message_id_value' + + +def test_update_message_rest_required_fields(request_type=gc_message.UpdateMessageRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_message._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_message._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gc_message.Message() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "put", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gc_message.Message.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_message(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_message_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_message._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "updateMask", )) & set(("message", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_message_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "post_update_message") as post, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "pre_update_message") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gc_message.UpdateMessageRequest.pb(gc_message.UpdateMessageRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gc_message.Message.to_json(gc_message.Message()) + + request = gc_message.UpdateMessageRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gc_message.Message() + + client.update_message(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_message_rest_bad_request(transport: str = 'rest', request_type=gc_message.UpdateMessageRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'message': {'name': 'spaces/sample1/messages/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_message(request) + + +def test_update_message_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gc_message.Message() + + # get arguments that satisfy an http rule for this method + sample_request = {'message': {'name': 'spaces/sample1/messages/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + message=gc_message.Message(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gc_message.Message.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_message(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{message.name=spaces/*/messages/*}" % client.transport._host, args[1]) + + +def test_update_message_rest_flattened_error(transport: str = 'rest'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_message( + gc_message.UpdateMessageRequest(), + message=gc_message.Message(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_message_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + message.DeleteMessageRequest, + dict, +]) +def test_delete_message_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'spaces/sample1/messages/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_message(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_message_rest_required_fields(request_type=message.DeleteMessageRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_message._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_message._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("force", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_message(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_message_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_message._get_unset_required_fields({}) + assert set(unset_fields) == (set(("force", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_message_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "pre_delete_message") as pre: + pre.assert_not_called() + pb_message = message.DeleteMessageRequest.pb(message.DeleteMessageRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = message.DeleteMessageRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_message(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_message_rest_bad_request(transport: str = 'rest', request_type=message.DeleteMessageRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'spaces/sample1/messages/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_message(request) + + +def test_delete_message_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'spaces/sample1/messages/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_message(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=spaces/*/messages/*}" % client.transport._host, args[1]) + + +def test_delete_message_rest_flattened_error(transport: str = 'rest'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_message( + message.DeleteMessageRequest(), + name='name_value', + ) + + +def test_delete_message_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + attachment.GetAttachmentRequest, + dict, +]) +def test_get_attachment_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'spaces/sample1/messages/sample2/attachments/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = attachment.Attachment( + name='name_value', + content_name='content_name_value', + content_type='content_type_value', + thumbnail_uri='thumbnail_uri_value', + download_uri='download_uri_value', + source=attachment.Attachment.Source.DRIVE_FILE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = attachment.Attachment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_attachment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, attachment.Attachment) + assert response.name == 'name_value' + assert response.content_name == 'content_name_value' + assert response.content_type == 'content_type_value' + assert response.thumbnail_uri == 'thumbnail_uri_value' + assert response.download_uri == 'download_uri_value' + assert response.source == attachment.Attachment.Source.DRIVE_FILE + + +def test_get_attachment_rest_required_fields(request_type=attachment.GetAttachmentRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_attachment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_attachment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = attachment.Attachment() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = attachment.Attachment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_attachment(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_attachment_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_attachment._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_attachment_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "post_get_attachment") as post, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "pre_get_attachment") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = attachment.GetAttachmentRequest.pb(attachment.GetAttachmentRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = attachment.Attachment.to_json(attachment.Attachment()) + + request = attachment.GetAttachmentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = attachment.Attachment() + + client.get_attachment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_attachment_rest_bad_request(transport: str = 'rest', request_type=attachment.GetAttachmentRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'spaces/sample1/messages/sample2/attachments/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_attachment(request) + + +def test_get_attachment_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = attachment.Attachment() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'spaces/sample1/messages/sample2/attachments/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = attachment.Attachment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_attachment(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=spaces/*/messages/*/attachments/*}" % client.transport._host, args[1]) + + +def test_get_attachment_rest_flattened_error(transport: str = 'rest'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_attachment( + attachment.GetAttachmentRequest(), + name='name_value', + ) + + +def test_get_attachment_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + attachment.UploadAttachmentRequest, + dict, +]) +def test_upload_attachment_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'spaces/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = attachment.UploadAttachmentResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = attachment.UploadAttachmentResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.upload_attachment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, attachment.UploadAttachmentResponse) + + +def test_upload_attachment_rest_required_fields(request_type=attachment.UploadAttachmentRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["filename"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).upload_attachment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["filename"] = 'filename_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).upload_attachment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "filename" in jsonified_request + assert jsonified_request["filename"] == 'filename_value' + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = attachment.UploadAttachmentResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = attachment.UploadAttachmentResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.upload_attachment(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_upload_attachment_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.upload_attachment._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "filename", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_upload_attachment_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "post_upload_attachment") as post, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "pre_upload_attachment") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = attachment.UploadAttachmentRequest.pb(attachment.UploadAttachmentRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = attachment.UploadAttachmentResponse.to_json(attachment.UploadAttachmentResponse()) + + request = attachment.UploadAttachmentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = attachment.UploadAttachmentResponse() + + client.upload_attachment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_upload_attachment_rest_bad_request(transport: str = 'rest', request_type=attachment.UploadAttachmentRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'spaces/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.upload_attachment(request) + + +def test_upload_attachment_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + space.ListSpacesRequest, + dict, +]) +def test_list_spaces_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = space.ListSpacesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = space.ListSpacesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_spaces(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSpacesPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_spaces_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "post_list_spaces") as post, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "pre_list_spaces") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = space.ListSpacesRequest.pb(space.ListSpacesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = space.ListSpacesResponse.to_json(space.ListSpacesResponse()) + + request = space.ListSpacesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = space.ListSpacesResponse() + + client.list_spaces(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_spaces_rest_bad_request(transport: str = 'rest', request_type=space.ListSpacesRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_spaces(request) + + +def test_list_spaces_rest_pager(transport: str = 'rest'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + space.ListSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + space.Space(), + ], + next_page_token='abc', + ), + space.ListSpacesResponse( + spaces=[], + next_page_token='def', + ), + space.ListSpacesResponse( + spaces=[ + space.Space(), + ], + next_page_token='ghi', + ), + space.ListSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(space.ListSpacesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {} + + pager = client.list_spaces(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, space.Space) + for i in results) + + pages = list(client.list_spaces(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + space.GetSpaceRequest, + dict, +]) +def test_get_space_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'spaces/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = space.Space( + name='name_value', + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name='display_name_value', + external_user_allowed=True, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = space.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_space(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, space.Space) + assert response.name == 'name_value' + assert response.type_ == space.Space.Type.ROOM + assert response.space_type == space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == 'display_name_value' + assert response.external_user_allowed is True + assert response.space_threading_state == space.Space.SpaceThreadingState.THREADED_MESSAGES + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +def test_get_space_rest_required_fields(request_type=space.GetSpaceRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_space._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_space._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = space.Space() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = space.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_space(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_space_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_space._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_space_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "post_get_space") as post, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "pre_get_space") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = space.GetSpaceRequest.pb(space.GetSpaceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = space.Space.to_json(space.Space()) + + request = space.GetSpaceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = space.Space() + + client.get_space(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_space_rest_bad_request(transport: str = 'rest', request_type=space.GetSpaceRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'spaces/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_space(request) + + +def test_get_space_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = space.Space() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'spaces/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = space.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_space(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=spaces/*}" % client.transport._host, args[1]) + + +def test_get_space_rest_flattened_error(transport: str = 'rest'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_space( + space.GetSpaceRequest(), + name='name_value', + ) + + +def test_get_space_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + gc_space.CreateSpaceRequest, + dict, +]) +def test_create_space_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request_init["space"] = {'name': 'name_value', 'type_': 1, 'space_type': 1, 'single_user_bot_dm': True, 'threaded': True, 'display_name': 'display_name_value', 'external_user_allowed': True, 'space_threading_state': 2, 'space_details': {'description': 'description_value', 'guidelines': 'guidelines_value'}, 'space_history_state': 1, 'import_mode': True, 'create_time': {'seconds': 751, 'nanos': 543}, 'admin_installed': True} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gc_space.CreateSpaceRequest.meta.fields["space"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["space"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["space"][field])): + del request_init["space"][field][i][subfield] + else: + del request_init["space"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gc_space.Space( + name='name_value', + type_=gc_space.Space.Type.ROOM, + space_type=gc_space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name='display_name_value', + external_user_allowed=True, + space_threading_state=gc_space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gc_space.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_space(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_space.Space) + assert response.name == 'name_value' + assert response.type_ == gc_space.Space.Type.ROOM + assert response.space_type == gc_space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == 'display_name_value' + assert response.external_user_allowed is True + assert response.space_threading_state == gc_space.Space.SpaceThreadingState.THREADED_MESSAGES + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +def test_create_space_rest_required_fields(request_type=gc_space.CreateSpaceRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_space._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_space._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gc_space.Space() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gc_space.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_space(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_space_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_space._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("space", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_space_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "post_create_space") as post, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "pre_create_space") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gc_space.CreateSpaceRequest.pb(gc_space.CreateSpaceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gc_space.Space.to_json(gc_space.Space()) + + request = gc_space.CreateSpaceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gc_space.Space() + + client.create_space(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_space_rest_bad_request(transport: str = 'rest', request_type=gc_space.CreateSpaceRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_space(request) + + +def test_create_space_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gc_space.Space() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + space=gc_space.Space(name='name_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gc_space.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_space(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/spaces" % client.transport._host, args[1]) + + +def test_create_space_rest_flattened_error(transport: str = 'rest'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_space( + gc_space.CreateSpaceRequest(), + space=gc_space.Space(name='name_value'), + ) + + +def test_create_space_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + space_setup.SetUpSpaceRequest, + dict, +]) +def test_set_up_space_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = space.Space( + name='name_value', + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name='display_name_value', + external_user_allowed=True, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = space.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.set_up_space(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, space.Space) + assert response.name == 'name_value' + assert response.type_ == space.Space.Type.ROOM + assert response.space_type == space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == 'display_name_value' + assert response.external_user_allowed is True + assert response.space_threading_state == space.Space.SpaceThreadingState.THREADED_MESSAGES + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +def test_set_up_space_rest_required_fields(request_type=space_setup.SetUpSpaceRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_up_space._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_up_space._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = space.Space() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = space.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.set_up_space(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_up_space_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_up_space._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("space", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_up_space_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "post_set_up_space") as post, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "pre_set_up_space") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = space_setup.SetUpSpaceRequest.pb(space_setup.SetUpSpaceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = space.Space.to_json(space.Space()) + + request = space_setup.SetUpSpaceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = space.Space() + + client.set_up_space(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_up_space_rest_bad_request(transport: str = 'rest', request_type=space_setup.SetUpSpaceRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_up_space(request) + + +def test_set_up_space_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + gc_space.UpdateSpaceRequest, + dict, +]) +def test_update_space_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'space': {'name': 'spaces/sample1'}} + request_init["space"] = {'name': 'spaces/sample1', 'type_': 1, 'space_type': 1, 'single_user_bot_dm': True, 'threaded': True, 'display_name': 'display_name_value', 'external_user_allowed': True, 'space_threading_state': 2, 'space_details': {'description': 'description_value', 'guidelines': 'guidelines_value'}, 'space_history_state': 1, 'import_mode': True, 'create_time': {'seconds': 751, 'nanos': 543}, 'admin_installed': True} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gc_space.UpdateSpaceRequest.meta.fields["space"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["space"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["space"][field])): + del request_init["space"][field][i][subfield] + else: + del request_init["space"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gc_space.Space( + name='name_value', + type_=gc_space.Space.Type.ROOM, + space_type=gc_space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name='display_name_value', + external_user_allowed=True, + space_threading_state=gc_space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gc_space.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_space(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_space.Space) + assert response.name == 'name_value' + assert response.type_ == gc_space.Space.Type.ROOM + assert response.space_type == gc_space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == 'display_name_value' + assert response.external_user_allowed is True + assert response.space_threading_state == gc_space.Space.SpaceThreadingState.THREADED_MESSAGES + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +def test_update_space_rest_required_fields(request_type=gc_space.UpdateSpaceRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_space._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_space._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gc_space.Space() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gc_space.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_space(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_space_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_space._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("space", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_space_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "post_update_space") as post, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "pre_update_space") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gc_space.UpdateSpaceRequest.pb(gc_space.UpdateSpaceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gc_space.Space.to_json(gc_space.Space()) + + request = gc_space.UpdateSpaceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gc_space.Space() + + client.update_space(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_space_rest_bad_request(transport: str = 'rest', request_type=gc_space.UpdateSpaceRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'space': {'name': 'spaces/sample1'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_space(request) + + +def test_update_space_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gc_space.Space() + + # get arguments that satisfy an http rule for this method + sample_request = {'space': {'name': 'spaces/sample1'}} + + # get truthy value for each flattened field + mock_args = dict( + space=gc_space.Space(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gc_space.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_space(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{space.name=spaces/*}" % client.transport._host, args[1]) + + +def test_update_space_rest_flattened_error(transport: str = 'rest'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_space( + gc_space.UpdateSpaceRequest(), + space=gc_space.Space(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_space_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + space.DeleteSpaceRequest, + dict, +]) +def test_delete_space_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'spaces/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_space(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_space_rest_required_fields(request_type=space.DeleteSpaceRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_space._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_space._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_space(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_space_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_space._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_space_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "pre_delete_space") as pre: + pre.assert_not_called() + pb_message = space.DeleteSpaceRequest.pb(space.DeleteSpaceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = space.DeleteSpaceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_space(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_space_rest_bad_request(transport: str = 'rest', request_type=space.DeleteSpaceRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'spaces/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_space(request) + + +def test_delete_space_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'spaces/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_space(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=spaces/*}" % client.transport._host, args[1]) + + +def test_delete_space_rest_flattened_error(transport: str = 'rest'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_space( + space.DeleteSpaceRequest(), + name='name_value', + ) + + +def test_delete_space_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + space.CompleteImportSpaceRequest, + dict, +]) +def test_complete_import_space_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'spaces/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = space.CompleteImportSpaceResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = space.CompleteImportSpaceResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.complete_import_space(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, space.CompleteImportSpaceResponse) + + +def test_complete_import_space_rest_required_fields(request_type=space.CompleteImportSpaceRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).complete_import_space._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).complete_import_space._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = space.CompleteImportSpaceResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = space.CompleteImportSpaceResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.complete_import_space(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_complete_import_space_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.complete_import_space._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_complete_import_space_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "post_complete_import_space") as post, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "pre_complete_import_space") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = space.CompleteImportSpaceRequest.pb(space.CompleteImportSpaceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = space.CompleteImportSpaceResponse.to_json(space.CompleteImportSpaceResponse()) + + request = space.CompleteImportSpaceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = space.CompleteImportSpaceResponse() + + client.complete_import_space(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_complete_import_space_rest_bad_request(transport: str = 'rest', request_type=space.CompleteImportSpaceRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'spaces/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.complete_import_space(request) + + +def test_complete_import_space_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + space.FindDirectMessageRequest, + dict, +]) +def test_find_direct_message_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = space.Space( + name='name_value', + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name='display_name_value', + external_user_allowed=True, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = space.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.find_direct_message(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, space.Space) + assert response.name == 'name_value' + assert response.type_ == space.Space.Type.ROOM + assert response.space_type == space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == 'display_name_value' + assert response.external_user_allowed is True + assert response.space_threading_state == space.Space.SpaceThreadingState.THREADED_MESSAGES + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +def test_find_direct_message_rest_required_fields(request_type=space.FindDirectMessageRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "name" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).find_direct_message._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "name" in jsonified_request + assert jsonified_request["name"] == request_init["name"] + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).find_direct_message._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("name", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = space.Space() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = space.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.find_direct_message(request) + + expected_params = [ + ( + "name", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_find_direct_message_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.find_direct_message._get_unset_required_fields({}) + assert set(unset_fields) == (set(("name", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_find_direct_message_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "post_find_direct_message") as post, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "pre_find_direct_message") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = space.FindDirectMessageRequest.pb(space.FindDirectMessageRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = space.Space.to_json(space.Space()) + + request = space.FindDirectMessageRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = space.Space() + + client.find_direct_message(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_find_direct_message_rest_bad_request(transport: str = 'rest', request_type=space.FindDirectMessageRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.find_direct_message(request) + + +def test_find_direct_message_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + gc_membership.CreateMembershipRequest, + dict, +]) +def test_create_membership_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'spaces/sample1'} + request_init["membership"] = {'name': 'name_value', 'state': 1, 'role': 1, 'member': {'name': 'name_value', 'display_name': 'display_name_value', 'domain_id': 'domain_id_value', 'type_': 1, 'is_anonymous': True}, 'group_member': {'name': 'name_value'}, 'create_time': {'seconds': 751, 'nanos': 543}, 'delete_time': {}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gc_membership.CreateMembershipRequest.meta.fields["membership"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["membership"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["membership"][field])): + del request_init["membership"][field][i][subfield] + else: + del request_init["membership"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gc_membership.Membership( + name='name_value', + state=gc_membership.Membership.MembershipState.JOINED, + role=gc_membership.Membership.MembershipRole.ROLE_MEMBER, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gc_membership.Membership.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_membership(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_membership.Membership) + assert response.name == 'name_value' + assert response.state == gc_membership.Membership.MembershipState.JOINED + assert response.role == gc_membership.Membership.MembershipRole.ROLE_MEMBER + + +def test_create_membership_rest_required_fields(request_type=gc_membership.CreateMembershipRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gc_membership.Membership() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gc_membership.Membership.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_membership(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_membership_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_membership._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "membership", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_membership_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "post_create_membership") as post, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "pre_create_membership") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gc_membership.CreateMembershipRequest.pb(gc_membership.CreateMembershipRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gc_membership.Membership.to_json(gc_membership.Membership()) + + request = gc_membership.CreateMembershipRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gc_membership.Membership() + + client.create_membership(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_membership_rest_bad_request(transport: str = 'rest', request_type=gc_membership.CreateMembershipRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'spaces/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_membership(request) + + +def test_create_membership_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gc_membership.Membership() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'spaces/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + membership=gc_membership.Membership(name='name_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gc_membership.Membership.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_membership(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=spaces/*}/members" % client.transport._host, args[1]) + + +def test_create_membership_rest_flattened_error(transport: str = 'rest'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_membership( + gc_membership.CreateMembershipRequest(), + parent='parent_value', + membership=gc_membership.Membership(name='name_value'), + ) + + +def test_create_membership_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + gc_membership.UpdateMembershipRequest, + dict, +]) +def test_update_membership_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'membership': {'name': 'spaces/sample1/members/sample2'}} + request_init["membership"] = {'name': 'spaces/sample1/members/sample2', 'state': 1, 'role': 1, 'member': {'name': 'name_value', 'display_name': 'display_name_value', 'domain_id': 'domain_id_value', 'type_': 1, 'is_anonymous': True}, 'group_member': {'name': 'name_value'}, 'create_time': {'seconds': 751, 'nanos': 543}, 'delete_time': {}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gc_membership.UpdateMembershipRequest.meta.fields["membership"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["membership"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["membership"][field])): + del request_init["membership"][field][i][subfield] + else: + del request_init["membership"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gc_membership.Membership( + name='name_value', + state=gc_membership.Membership.MembershipState.JOINED, + role=gc_membership.Membership.MembershipRole.ROLE_MEMBER, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gc_membership.Membership.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_membership(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_membership.Membership) + assert response.name == 'name_value' + assert response.state == gc_membership.Membership.MembershipState.JOINED + assert response.role == gc_membership.Membership.MembershipRole.ROLE_MEMBER + + +def test_update_membership_rest_required_fields(request_type=gc_membership.UpdateMembershipRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_membership._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gc_membership.Membership() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gc_membership.Membership.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_membership(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_membership_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_membership._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("membership", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_membership_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "post_update_membership") as post, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "pre_update_membership") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gc_membership.UpdateMembershipRequest.pb(gc_membership.UpdateMembershipRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gc_membership.Membership.to_json(gc_membership.Membership()) + + request = gc_membership.UpdateMembershipRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gc_membership.Membership() + + client.update_membership(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_membership_rest_bad_request(transport: str = 'rest', request_type=gc_membership.UpdateMembershipRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'membership': {'name': 'spaces/sample1/members/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_membership(request) + + +def test_update_membership_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gc_membership.Membership() + + # get arguments that satisfy an http rule for this method + sample_request = {'membership': {'name': 'spaces/sample1/members/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + membership=gc_membership.Membership(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gc_membership.Membership.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_membership(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{membership.name=spaces/*/members/*}" % client.transport._host, args[1]) + + +def test_update_membership_rest_flattened_error(transport: str = 'rest'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_membership( + gc_membership.UpdateMembershipRequest(), + membership=gc_membership.Membership(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_membership_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + membership.DeleteMembershipRequest, + dict, +]) +def test_delete_membership_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'spaces/sample1/members/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = membership.Membership( + name='name_value', + state=membership.Membership.MembershipState.JOINED, + role=membership.Membership.MembershipRole.ROLE_MEMBER, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = membership.Membership.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_membership(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.Membership) + assert response.name == 'name_value' + assert response.state == membership.Membership.MembershipState.JOINED + assert response.role == membership.Membership.MembershipRole.ROLE_MEMBER + + +def test_delete_membership_rest_required_fields(request_type=membership.DeleteMembershipRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = membership.Membership() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = membership.Membership.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_membership(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_membership_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_membership._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_membership_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "post_delete_membership") as post, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "pre_delete_membership") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = membership.DeleteMembershipRequest.pb(membership.DeleteMembershipRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = membership.Membership.to_json(membership.Membership()) + + request = membership.DeleteMembershipRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = membership.Membership() + + client.delete_membership(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_membership_rest_bad_request(transport: str = 'rest', request_type=membership.DeleteMembershipRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'spaces/sample1/members/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_membership(request) + + +def test_delete_membership_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = membership.Membership() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'spaces/sample1/members/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = membership.Membership.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_membership(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=spaces/*/members/*}" % client.transport._host, args[1]) + + +def test_delete_membership_rest_flattened_error(transport: str = 'rest'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_membership( + membership.DeleteMembershipRequest(), + name='name_value', + ) + + +def test_delete_membership_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + gc_reaction.CreateReactionRequest, + dict, +]) +def test_create_reaction_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'spaces/sample1/messages/sample2'} + request_init["reaction"] = {'name': 'name_value', 'user': {'name': 'name_value', 'display_name': 'display_name_value', 'domain_id': 'domain_id_value', 'type_': 1, 'is_anonymous': True}, 'emoji': {'unicode': 'unicode_value', 'custom_emoji': {'uid': 'uid_value'}}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gc_reaction.CreateReactionRequest.meta.fields["reaction"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["reaction"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["reaction"][field])): + del request_init["reaction"][field][i][subfield] + else: + del request_init["reaction"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gc_reaction.Reaction( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gc_reaction.Reaction.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_reaction(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_reaction.Reaction) + assert response.name == 'name_value' + + +def test_create_reaction_rest_required_fields(request_type=gc_reaction.CreateReactionRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_reaction._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_reaction._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gc_reaction.Reaction() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gc_reaction.Reaction.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_reaction(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_reaction_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_reaction._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "reaction", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_reaction_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "post_create_reaction") as post, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "pre_create_reaction") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gc_reaction.CreateReactionRequest.pb(gc_reaction.CreateReactionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gc_reaction.Reaction.to_json(gc_reaction.Reaction()) + + request = gc_reaction.CreateReactionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gc_reaction.Reaction() + + client.create_reaction(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_reaction_rest_bad_request(transport: str = 'rest', request_type=gc_reaction.CreateReactionRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'spaces/sample1/messages/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_reaction(request) + + +def test_create_reaction_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gc_reaction.Reaction() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'spaces/sample1/messages/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + reaction=gc_reaction.Reaction(name='name_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gc_reaction.Reaction.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_reaction(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=spaces/*/messages/*}/reactions" % client.transport._host, args[1]) + + +def test_create_reaction_rest_flattened_error(transport: str = 'rest'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_reaction( + gc_reaction.CreateReactionRequest(), + parent='parent_value', + reaction=gc_reaction.Reaction(name='name_value'), + ) + + +def test_create_reaction_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + reaction.ListReactionsRequest, + dict, +]) +def test_list_reactions_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'spaces/sample1/messages/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = reaction.ListReactionsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = reaction.ListReactionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_reactions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListReactionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_reactions_rest_required_fields(request_type=reaction.ListReactionsRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_reactions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_reactions._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = reaction.ListReactionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = reaction.ListReactionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_reactions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_reactions_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_reactions._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_reactions_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "post_list_reactions") as post, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "pre_list_reactions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reaction.ListReactionsRequest.pb(reaction.ListReactionsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = reaction.ListReactionsResponse.to_json(reaction.ListReactionsResponse()) + + request = reaction.ListReactionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = reaction.ListReactionsResponse() + + client.list_reactions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_reactions_rest_bad_request(transport: str = 'rest', request_type=reaction.ListReactionsRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'spaces/sample1/messages/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_reactions(request) + + +def test_list_reactions_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = reaction.ListReactionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'spaces/sample1/messages/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = reaction.ListReactionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_reactions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=spaces/*/messages/*}/reactions" % client.transport._host, args[1]) + + +def test_list_reactions_rest_flattened_error(transport: str = 'rest'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_reactions( + reaction.ListReactionsRequest(), + parent='parent_value', + ) + + +def test_list_reactions_rest_pager(transport: str = 'rest'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + reaction.Reaction(), + reaction.Reaction(), + ], + next_page_token='abc', + ), + reaction.ListReactionsResponse( + reactions=[], + next_page_token='def', + ), + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + ], + next_page_token='ghi', + ), + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + reaction.Reaction(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(reaction.ListReactionsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'spaces/sample1/messages/sample2'} + + pager = client.list_reactions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, reaction.Reaction) + for i in results) + + pages = list(client.list_reactions(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + reaction.DeleteReactionRequest, + dict, +]) +def test_delete_reaction_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'spaces/sample1/messages/sample2/reactions/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_reaction(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_reaction_rest_required_fields(request_type=reaction.DeleteReactionRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_reaction._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_reaction._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_reaction(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_reaction_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_reaction._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_reaction_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "pre_delete_reaction") as pre: + pre.assert_not_called() + pb_message = reaction.DeleteReactionRequest.pb(reaction.DeleteReactionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = reaction.DeleteReactionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_reaction(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_reaction_rest_bad_request(transport: str = 'rest', request_type=reaction.DeleteReactionRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'spaces/sample1/messages/sample2/reactions/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_reaction(request) + + +def test_delete_reaction_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'spaces/sample1/messages/sample2/reactions/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_reaction(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=spaces/*/messages/*/reactions/*}" % client.transport._host, args[1]) + + +def test_delete_reaction_rest_flattened_error(transport: str = 'rest'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_reaction( + reaction.DeleteReactionRequest(), + name='name_value', + ) + + +def test_delete_reaction_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + space_read_state.GetSpaceReadStateRequest, + dict, +]) +def test_get_space_read_state_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'users/sample1/spaces/sample2/spaceReadState'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = space_read_state.SpaceReadState( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = space_read_state.SpaceReadState.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_space_read_state(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, space_read_state.SpaceReadState) + assert response.name == 'name_value' + + +def test_get_space_read_state_rest_required_fields(request_type=space_read_state.GetSpaceReadStateRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_space_read_state._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_space_read_state._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = space_read_state.SpaceReadState() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = space_read_state.SpaceReadState.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_space_read_state(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_space_read_state_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_space_read_state._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_space_read_state_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "post_get_space_read_state") as post, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "pre_get_space_read_state") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = space_read_state.GetSpaceReadStateRequest.pb(space_read_state.GetSpaceReadStateRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = space_read_state.SpaceReadState.to_json(space_read_state.SpaceReadState()) + + request = space_read_state.GetSpaceReadStateRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = space_read_state.SpaceReadState() + + client.get_space_read_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_space_read_state_rest_bad_request(transport: str = 'rest', request_type=space_read_state.GetSpaceReadStateRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'users/sample1/spaces/sample2/spaceReadState'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_space_read_state(request) + + +def test_get_space_read_state_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = space_read_state.SpaceReadState() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'users/sample1/spaces/sample2/spaceReadState'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = space_read_state.SpaceReadState.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_space_read_state(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=users/*/spaces/*/spaceReadState}" % client.transport._host, args[1]) + + +def test_get_space_read_state_rest_flattened_error(transport: str = 'rest'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_space_read_state( + space_read_state.GetSpaceReadStateRequest(), + name='name_value', + ) + + +def test_get_space_read_state_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + gc_space_read_state.UpdateSpaceReadStateRequest, + dict, +]) +def test_update_space_read_state_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'space_read_state': {'name': 'users/sample1/spaces/sample2/spaceReadState'}} + request_init["space_read_state"] = {'name': 'users/sample1/spaces/sample2/spaceReadState', 'last_read_time': {'seconds': 751, 'nanos': 543}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gc_space_read_state.UpdateSpaceReadStateRequest.meta.fields["space_read_state"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["space_read_state"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["space_read_state"][field])): + del request_init["space_read_state"][field][i][subfield] + else: + del request_init["space_read_state"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gc_space_read_state.SpaceReadState( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gc_space_read_state.SpaceReadState.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_space_read_state(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_space_read_state.SpaceReadState) + assert response.name == 'name_value' + + +def test_update_space_read_state_rest_required_fields(request_type=gc_space_read_state.UpdateSpaceReadStateRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_space_read_state._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_space_read_state._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gc_space_read_state.SpaceReadState() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gc_space_read_state.SpaceReadState.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_space_read_state(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_space_read_state_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_space_read_state._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("spaceReadState", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_space_read_state_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "post_update_space_read_state") as post, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "pre_update_space_read_state") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gc_space_read_state.UpdateSpaceReadStateRequest.pb(gc_space_read_state.UpdateSpaceReadStateRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gc_space_read_state.SpaceReadState.to_json(gc_space_read_state.SpaceReadState()) + + request = gc_space_read_state.UpdateSpaceReadStateRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gc_space_read_state.SpaceReadState() + + client.update_space_read_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_space_read_state_rest_bad_request(transport: str = 'rest', request_type=gc_space_read_state.UpdateSpaceReadStateRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'space_read_state': {'name': 'users/sample1/spaces/sample2/spaceReadState'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_space_read_state(request) + + +def test_update_space_read_state_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gc_space_read_state.SpaceReadState() + + # get arguments that satisfy an http rule for this method + sample_request = {'space_read_state': {'name': 'users/sample1/spaces/sample2/spaceReadState'}} + + # get truthy value for each flattened field + mock_args = dict( + space_read_state=gc_space_read_state.SpaceReadState(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gc_space_read_state.SpaceReadState.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_space_read_state(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{space_read_state.name=users/*/spaces/*/spaceReadState}" % client.transport._host, args[1]) + + +def test_update_space_read_state_rest_flattened_error(transport: str = 'rest'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_space_read_state( + gc_space_read_state.UpdateSpaceReadStateRequest(), + space_read_state=gc_space_read_state.SpaceReadState(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_space_read_state_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + thread_read_state.GetThreadReadStateRequest, + dict, +]) +def test_get_thread_read_state_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'users/sample1/spaces/sample2/threads/sample3/threadReadState'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = thread_read_state.ThreadReadState( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = thread_read_state.ThreadReadState.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_thread_read_state(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, thread_read_state.ThreadReadState) + assert response.name == 'name_value' + + +def test_get_thread_read_state_rest_required_fields(request_type=thread_read_state.GetThreadReadStateRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_thread_read_state._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_thread_read_state._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = thread_read_state.ThreadReadState() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = thread_read_state.ThreadReadState.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_thread_read_state(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_thread_read_state_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_thread_read_state._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_thread_read_state_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "post_get_thread_read_state") as post, \ + mock.patch.object(transports.ChatServiceRestInterceptor, "pre_get_thread_read_state") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = thread_read_state.GetThreadReadStateRequest.pb(thread_read_state.GetThreadReadStateRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = thread_read_state.ThreadReadState.to_json(thread_read_state.ThreadReadState()) + + request = thread_read_state.GetThreadReadStateRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = thread_read_state.ThreadReadState() + + client.get_thread_read_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_thread_read_state_rest_bad_request(transport: str = 'rest', request_type=thread_read_state.GetThreadReadStateRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'users/sample1/spaces/sample2/threads/sample3/threadReadState'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_thread_read_state(request) + + +def test_get_thread_read_state_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = thread_read_state.ThreadReadState() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'users/sample1/spaces/sample2/threads/sample3/threadReadState'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = thread_read_state.ThreadReadState.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_thread_read_state(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=users/*/spaces/*/threads/*/threadReadState}" % client.transport._host, args[1]) + + +def test_get_thread_read_state_rest_flattened_error(transport: str = 'rest'): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_thread_read_state( + thread_read_state.GetThreadReadStateRequest(), + name='name_value', + ) + + +def test_get_thread_read_state_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ChatServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ChatServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ChatServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ChatServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ChatServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ChatServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ChatServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ChatServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ChatServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ChatServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ChatServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ChatServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ChatServiceGrpcTransport, + transports.ChatServiceGrpcAsyncIOTransport, + transports.ChatServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = ChatServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ChatServiceGrpcTransport, + ) + +def test_chat_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ChatServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_chat_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.apps.chat_v1.services.chat_service.transports.ChatServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ChatServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_message', + 'list_messages', + 'list_memberships', + 'get_membership', + 'get_message', + 'update_message', + 'delete_message', + 'get_attachment', + 'upload_attachment', + 'list_spaces', + 'get_space', + 'create_space', + 'set_up_space', + 'update_space', + 'delete_space', + 'complete_import_space', + 'find_direct_message', + 'create_membership', + 'update_membership', + 'delete_membership', + 'create_reaction', + 'list_reactions', + 'delete_reaction', + 'get_space_read_state', + 'update_space_read_state', + 'get_thread_read_state', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_chat_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.apps.chat_v1.services.chat_service.transports.ChatServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ChatServiceTransport( + 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/chat.bot', + 'https://www.googleapis.com/auth/chat.delete', + 'https://www.googleapis.com/auth/chat.import', + 'https://www.googleapis.com/auth/chat.memberships', + 'https://www.googleapis.com/auth/chat.memberships.app', + 'https://www.googleapis.com/auth/chat.memberships.readonly', + 'https://www.googleapis.com/auth/chat.messages', + 'https://www.googleapis.com/auth/chat.messages.create', + 'https://www.googleapis.com/auth/chat.messages.reactions', + 'https://www.googleapis.com/auth/chat.messages.reactions.create', + 'https://www.googleapis.com/auth/chat.messages.reactions.readonly', + 'https://www.googleapis.com/auth/chat.messages.readonly', + 'https://www.googleapis.com/auth/chat.spaces', + 'https://www.googleapis.com/auth/chat.spaces.create', + 'https://www.googleapis.com/auth/chat.spaces.readonly', + 'https://www.googleapis.com/auth/chat.users.readstate', + 'https://www.googleapis.com/auth/chat.users.readstate.readonly', +), + quota_project_id="octopus", + ) + + +def test_chat_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.apps.chat_v1.services.chat_service.transports.ChatServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ChatServiceTransport() + adc.assert_called_once() + + +def test_chat_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ChatServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/chat.bot', + 'https://www.googleapis.com/auth/chat.delete', + 'https://www.googleapis.com/auth/chat.import', + 'https://www.googleapis.com/auth/chat.memberships', + 'https://www.googleapis.com/auth/chat.memberships.app', + 'https://www.googleapis.com/auth/chat.memberships.readonly', + 'https://www.googleapis.com/auth/chat.messages', + 'https://www.googleapis.com/auth/chat.messages.create', + 'https://www.googleapis.com/auth/chat.messages.reactions', + 'https://www.googleapis.com/auth/chat.messages.reactions.create', + 'https://www.googleapis.com/auth/chat.messages.reactions.readonly', + 'https://www.googleapis.com/auth/chat.messages.readonly', + 'https://www.googleapis.com/auth/chat.spaces', + 'https://www.googleapis.com/auth/chat.spaces.create', + 'https://www.googleapis.com/auth/chat.spaces.readonly', + 'https://www.googleapis.com/auth/chat.users.readstate', + 'https://www.googleapis.com/auth/chat.users.readstate.readonly', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ChatServiceGrpcTransport, + transports.ChatServiceGrpcAsyncIOTransport, + ], +) +def test_chat_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/chat.bot', 'https://www.googleapis.com/auth/chat.delete', 'https://www.googleapis.com/auth/chat.import', 'https://www.googleapis.com/auth/chat.memberships', 'https://www.googleapis.com/auth/chat.memberships.app', 'https://www.googleapis.com/auth/chat.memberships.readonly', 'https://www.googleapis.com/auth/chat.messages', 'https://www.googleapis.com/auth/chat.messages.create', 'https://www.googleapis.com/auth/chat.messages.reactions', 'https://www.googleapis.com/auth/chat.messages.reactions.create', 'https://www.googleapis.com/auth/chat.messages.reactions.readonly', 'https://www.googleapis.com/auth/chat.messages.readonly', 'https://www.googleapis.com/auth/chat.spaces', 'https://www.googleapis.com/auth/chat.spaces.create', 'https://www.googleapis.com/auth/chat.spaces.readonly', 'https://www.googleapis.com/auth/chat.users.readstate', 'https://www.googleapis.com/auth/chat.users.readstate.readonly',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ChatServiceGrpcTransport, + transports.ChatServiceGrpcAsyncIOTransport, + transports.ChatServiceRestTransport, + ], +) +def test_chat_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ChatServiceGrpcTransport, grpc_helpers), + (transports.ChatServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_chat_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "chat.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/chat.bot', + 'https://www.googleapis.com/auth/chat.delete', + 'https://www.googleapis.com/auth/chat.import', + 'https://www.googleapis.com/auth/chat.memberships', + 'https://www.googleapis.com/auth/chat.memberships.app', + 'https://www.googleapis.com/auth/chat.memberships.readonly', + 'https://www.googleapis.com/auth/chat.messages', + 'https://www.googleapis.com/auth/chat.messages.create', + 'https://www.googleapis.com/auth/chat.messages.reactions', + 'https://www.googleapis.com/auth/chat.messages.reactions.create', + 'https://www.googleapis.com/auth/chat.messages.reactions.readonly', + 'https://www.googleapis.com/auth/chat.messages.readonly', + 'https://www.googleapis.com/auth/chat.spaces', + 'https://www.googleapis.com/auth/chat.spaces.create', + 'https://www.googleapis.com/auth/chat.spaces.readonly', + 'https://www.googleapis.com/auth/chat.users.readstate', + 'https://www.googleapis.com/auth/chat.users.readstate.readonly', +), + scopes=["1", "2"], + default_host="chat.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ChatServiceGrpcTransport, transports.ChatServiceGrpcAsyncIOTransport]) +def test_chat_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_chat_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.ChatServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_chat_service_host_no_port(transport_name): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='chat.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'chat.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://chat.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_chat_service_host_with_port(transport_name): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='chat.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'chat.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://chat.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_chat_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ChatServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ChatServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_message._session + session2 = client2.transport.create_message._session + assert session1 != session2 + session1 = client1.transport.list_messages._session + session2 = client2.transport.list_messages._session + assert session1 != session2 + session1 = client1.transport.list_memberships._session + session2 = client2.transport.list_memberships._session + assert session1 != session2 + session1 = client1.transport.get_membership._session + session2 = client2.transport.get_membership._session + assert session1 != session2 + session1 = client1.transport.get_message._session + session2 = client2.transport.get_message._session + assert session1 != session2 + session1 = client1.transport.update_message._session + session2 = client2.transport.update_message._session + assert session1 != session2 + session1 = client1.transport.delete_message._session + session2 = client2.transport.delete_message._session + assert session1 != session2 + session1 = client1.transport.get_attachment._session + session2 = client2.transport.get_attachment._session + assert session1 != session2 + session1 = client1.transport.upload_attachment._session + session2 = client2.transport.upload_attachment._session + assert session1 != session2 + session1 = client1.transport.list_spaces._session + session2 = client2.transport.list_spaces._session + assert session1 != session2 + session1 = client1.transport.get_space._session + session2 = client2.transport.get_space._session + assert session1 != session2 + session1 = client1.transport.create_space._session + session2 = client2.transport.create_space._session + assert session1 != session2 + session1 = client1.transport.set_up_space._session + session2 = client2.transport.set_up_space._session + assert session1 != session2 + session1 = client1.transport.update_space._session + session2 = client2.transport.update_space._session + assert session1 != session2 + session1 = client1.transport.delete_space._session + session2 = client2.transport.delete_space._session + assert session1 != session2 + session1 = client1.transport.complete_import_space._session + session2 = client2.transport.complete_import_space._session + assert session1 != session2 + session1 = client1.transport.find_direct_message._session + session2 = client2.transport.find_direct_message._session + assert session1 != session2 + session1 = client1.transport.create_membership._session + session2 = client2.transport.create_membership._session + assert session1 != session2 + session1 = client1.transport.update_membership._session + session2 = client2.transport.update_membership._session + assert session1 != session2 + session1 = client1.transport.delete_membership._session + session2 = client2.transport.delete_membership._session + assert session1 != session2 + session1 = client1.transport.create_reaction._session + session2 = client2.transport.create_reaction._session + assert session1 != session2 + session1 = client1.transport.list_reactions._session + session2 = client2.transport.list_reactions._session + assert session1 != session2 + session1 = client1.transport.delete_reaction._session + session2 = client2.transport.delete_reaction._session + assert session1 != session2 + session1 = client1.transport.get_space_read_state._session + session2 = client2.transport.get_space_read_state._session + assert session1 != session2 + session1 = client1.transport.update_space_read_state._session + session2 = client2.transport.update_space_read_state._session + assert session1 != session2 + session1 = client1.transport.get_thread_read_state._session + session2 = client2.transport.get_thread_read_state._session + assert session1 != session2 +def test_chat_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ChatServiceGrpcTransport( + 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_chat_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ChatServiceGrpcAsyncIOTransport( + 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.ChatServiceGrpcTransport, transports.ChatServiceGrpcAsyncIOTransport]) +def test_chat_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.ChatServiceGrpcTransport, transports.ChatServiceGrpcAsyncIOTransport]) +def test_chat_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_attachment_path(): + space = "squid" + message = "clam" + attachment = "whelk" + expected = "spaces/{space}/messages/{message}/attachments/{attachment}".format(space=space, message=message, attachment=attachment, ) + actual = ChatServiceClient.attachment_path(space, message, attachment) + assert expected == actual + + +def test_parse_attachment_path(): + expected = { + "space": "octopus", + "message": "oyster", + "attachment": "nudibranch", + } + path = ChatServiceClient.attachment_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_attachment_path(path) + assert expected == actual + +def test_membership_path(): + space = "cuttlefish" + member = "mussel" + expected = "spaces/{space}/members/{member}".format(space=space, member=member, ) + actual = ChatServiceClient.membership_path(space, member) + assert expected == actual + + +def test_parse_membership_path(): + expected = { + "space": "winkle", + "member": "nautilus", + } + path = ChatServiceClient.membership_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_membership_path(path) + assert expected == actual + +def test_message_path(): + space = "scallop" + message = "abalone" + expected = "spaces/{space}/messages/{message}".format(space=space, message=message, ) + actual = ChatServiceClient.message_path(space, message) + assert expected == actual + + +def test_parse_message_path(): + expected = { + "space": "squid", + "message": "clam", + } + path = ChatServiceClient.message_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_message_path(path) + assert expected == actual + +def test_quoted_message_metadata_path(): + space = "whelk" + message = "octopus" + quoted_message_metadata = "oyster" + expected = "spaces/{space}/messages/{message}/quotedMessageMetadata/{quoted_message_metadata}".format(space=space, message=message, quoted_message_metadata=quoted_message_metadata, ) + actual = ChatServiceClient.quoted_message_metadata_path(space, message, quoted_message_metadata) + assert expected == actual + + +def test_parse_quoted_message_metadata_path(): + expected = { + "space": "nudibranch", + "message": "cuttlefish", + "quoted_message_metadata": "mussel", + } + path = ChatServiceClient.quoted_message_metadata_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_quoted_message_metadata_path(path) + assert expected == actual + +def test_reaction_path(): + space = "winkle" + message = "nautilus" + reaction = "scallop" + expected = "spaces/{space}/messages/{message}/reactions/{reaction}".format(space=space, message=message, reaction=reaction, ) + actual = ChatServiceClient.reaction_path(space, message, reaction) + assert expected == actual + + +def test_parse_reaction_path(): + expected = { + "space": "abalone", + "message": "squid", + "reaction": "clam", + } + path = ChatServiceClient.reaction_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_reaction_path(path) + assert expected == actual + +def test_space_path(): + space = "whelk" + expected = "spaces/{space}".format(space=space, ) + actual = ChatServiceClient.space_path(space) + assert expected == actual + + +def test_parse_space_path(): + expected = { + "space": "octopus", + } + path = ChatServiceClient.space_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_space_path(path) + assert expected == actual + +def test_space_read_state_path(): + user = "oyster" + space = "nudibranch" + expected = "users/{user}/spaces/{space}/spaceReadState".format(user=user, space=space, ) + actual = ChatServiceClient.space_read_state_path(user, space) + assert expected == actual + + +def test_parse_space_read_state_path(): + expected = { + "user": "cuttlefish", + "space": "mussel", + } + path = ChatServiceClient.space_read_state_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_space_read_state_path(path) + assert expected == actual + +def test_thread_path(): + space = "winkle" + thread = "nautilus" + expected = "spaces/{space}/threads/{thread}".format(space=space, thread=thread, ) + actual = ChatServiceClient.thread_path(space, thread) + assert expected == actual + + +def test_parse_thread_path(): + expected = { + "space": "scallop", + "thread": "abalone", + } + path = ChatServiceClient.thread_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_thread_path(path) + assert expected == actual + +def test_thread_read_state_path(): + user = "squid" + space = "clam" + thread = "whelk" + expected = "users/{user}/spaces/{space}/threads/{thread}/threadReadState".format(user=user, space=space, thread=thread, ) + actual = ChatServiceClient.thread_read_state_path(user, space, thread) + assert expected == actual + + +def test_parse_thread_read_state_path(): + expected = { + "user": "octopus", + "space": "oyster", + "thread": "nudibranch", + } + path = ChatServiceClient.thread_read_state_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_thread_read_state_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ChatServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = ChatServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = ChatServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = ChatServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ChatServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = ChatServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = ChatServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = ChatServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.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 = ChatServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = ChatServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.ChatServiceTransport, '_prep_wrapped_messages') as prep: + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ChatServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ChatServiceClient.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 = ChatServiceAsyncClient( + 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 = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (ChatServiceClient, transports.ChatServiceGrpcTransport), + (ChatServiceAsyncClient, transports.ChatServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + )